text
stringlengths
8
267k
meta
dict
Q: Prompt browser download dialogue box Normal: <a href="/soundfile.mp3">download</a> The reason I can't do this is it's on a Wordpress installation with a plugin (wpaudio) which turns every mp3 filein the code into a mini player which when clicked streams the file. So that link above would appear as a link, with a play button beside it, when clicked would stream the file, and not prompt the download dialogue box. With 99% of the mp3 files on this site that's exactly what is needed. However for one file, I need to enable the user to click the linked word download, and get the save or open dialogue box, along with subsequent progress bar (if enabled in his browser preferences). PHP or Javascript is fine, either will do, anybody know how to get that working? A: According to the plugin site you linked to: Convert all mp3 links To turn every mp3 link on your blog into a player, select Convert all mp3 links in the WPaudio settings. Convert some mp3 links For any mp3 link you'd like to convert to a player, add the wpaudio class like this: <a href="http://url"class="wpaudio">Artist - Song</a> So, you probably just don't want to have to go give every link that class right? So, use JavaScript to do it. Give the links you don't want converted a class of no-wpaudio or something, and use JavaScript to add the class to all the links without the no-wpaudio class. Hopefully you are using jQuery: $("a[href$='.mp3']:not(.no-wpaudio)").addClass("wpaudio"); If not, what a pain, but it can be done. Let me know if you want the non-jQuery code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# / WinForms: Highlight only the first item of a ListBox on drag & drop In a ListBox: User should be able to pick multiple items by holding the CTRL key and seleting them. I have this working, but this ListBox needs to be able to do drag & drop of its items to another ListBox as well. Now, when it comes to drag & drop, if the user holds down the left button of the mouse and continue scrolling down or up with it, it selects all other items that are moused over, but I do not want this. When the user holds down the left button to move the item by drag & drop I want him to just be able to pick that item and all other items should not be selected. A: It sounds like your ListBox's SelectionMode property is set to MultiExtended. Setting this to MultiSimple should solve the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: boost_system renaming and symlink issues on ldd I have sample application that uses boost_system shared object. Now, because of certain scenarios, I have to support 2 different boost_system shared objects - one built with gcc and other with sun's cc in single directory - /home/mydir. Corresponding files are:- libboost_system_v1.so --dependency for--- applicationv1.so libboost_system_v2.so --dependency for--- applicationv2.so It is linked in the makefile as. ... $(BOOST_LIB_V1) -lboost_system_v1 Hence I renamed libboost_system_1_41_0.so to libboost_system_v1.so and also removed the softlink from $BOOST_HOME_V1/stage/lib. Now, when I try to build application - I do not get any errors. However ldd fails with:- ldd /home/mydir/applicationv1.so libboost_system.so.1.41.0 => not found ..................................... ..................................... ..................................... BOOST_HOME_v1/stage/lib(=BOOST_LIB_v1) looks like:- libboost_system_v1.so libboost_system_v1.a I am unable to understand - why does ldD still show libboost_system.so.1.41.0 as dependency instead of libboost_system_v1.so. I was expecting to see below o/p which is not what is obtained:- ldd /home/mydir/applicationv1.so libboost_system_v1.so -> /home/mydir/libboost_system_v1.so Can someone please explain if there is a solution to actually rename shared object and not deal with boost's default symlink? I checked src/build.jam - looks like linkage is done here - but I thought as long as I remove the softlink, rename the shared object and link with renamed shared object in makefile - there shouldn't be any issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OMR based software for .Net application I am looking for a Optical Mark Recognition software to read the scanned documents and automatically process them. These documents are created from a ASP.net Web application. Users will fill in those printed forms which have a barcode and then scan the same. If you have any idea or used it appreciate if you could suggest something. Thanks A: You can try something like http://en.wikipedia.org/wiki/Microsoft_Office_Document_Imaging for scanning documents. http://www.pixel-technology.com/freeware/tessnet2/ Tessnet 2 is an open source .Net based OMR assembly. I have never done barcode scanning or reader implementation, but I found this on google. Hope this helps. http://www.onbarcode.com/products/net_barcode_reader/ A: I've used Softek's Barcode Reader Toolkit for reading barcodes off of bitmaps before, and it worked very well. It's fairly configurable and speedy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Paypal Digital Goods - How to retrieve payer info? I just integrated the express checkout script from https://www.x.com/developers/community/blogs/ppmacole/another-digital-goods-demo into my site. I have a question. I'd like to keep track of all the sales with Freshbooks and I was wondering if it's possible to get the payer's information after the payment has been sent. I think I read somewhere that since it's a "digital goods" type checkout, it doesn't involve any address stuff. Any help would be greatly appreciated. Thanks! - Alain A: What information are you looking for? If it's any address-related information that would be correct; this is not collected with a Digital Goods checkout which, as the name implies, if intended to sell digital goods. If all you need is the fancy popup, I'd suggest looking at Embedded Payments which is part of the Adaptive suite of API's. See https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_APIntro "Using Embedded Payments".
{ "language": "en", "url": "https://stackoverflow.com/questions/7508309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Heuristic function for astar I need a good heuristic function for A star for the pen plotter/TSP, where each state of my system has: * *Path distance, that has been traveled *Point where the pen is at currently *Pen up/down The "pen up/down" refers to the state where, you have drawn a line just then or you are moving to a point to start a new line. Seeing as I have to travel through every point at some stage, the final goal state could be any point making any of the heuristics I've found on the internet impossible to use properly. I have tried the following, but failed to get a good heuristic from it: (g(x) divided by the sum of the total distance traveled) * number of states remaining (assuming you are alternating between drawing a line or moving to a new point to draw a line) I've also tried the euclidean distance between the current state and the goal state (find the closest possible goal state). This does not work since it gives you a heuristic of 0 because any state/point can be the goal state A: Taxicab Geometry may be a solution. I've experimented with code that uses the results for completing a sliding tile puzzle
{ "language": "en", "url": "https://stackoverflow.com/questions/7508312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mysql sorting of version numbers I have values like: 1.1.2 9.1 2.2 4 1.2.3.4 3.2.14 3.2.1.4.2 ..... I need to sort those values using mysql. The data type for this one is varbinary(300). The desired output will be like: 1.1.2 1.2.3.4 2.2 3.2.1.4.2 3.2.14 4 9.1 The Query is: select version_number from table order by version_number asc it does not give the correct sorting order. The desired output of this is: 1.1.2 1.2.3.4 2.2 3.2.1.4.2 3.2.14 4 9.1 The version numbers are up to 20 digits (like 1.2.3.4.5.6.7.8.9.2.34) and more also. There is no particular max size and the standard version is just like above mentioned. A: I would store it in three separate columns, one for each part of the version number. Make each column a TINYINT and even create an index across the 3 columns. That should make things simple. Then you can do: select CONCAT(v1,'.',v2,'.',v3) AS version_number FROM table ORDER BY v1 asc, v2 asc, v3 asc A: Try abusing the INET_ATON function to do the sorting like so: SELECT version_number FROM table ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(version_number,'.0.0.0'),'.',4)) This trick was originally posted on the mysql mailing list, so many thanks to the original poster, Michael Stassen! Here's what he had to say: If each part is no larger than 255, you can leverage INET_ATON() to do what you want (up to the 4th part). The trick is making each of these look like an IP first by using CONCAT to add '0.0.0' to make sure every row has at least 4 parts, then SUBSTRING_INDEX to pull out just the first 4 parts. Now, I must point out that because we are sorting on a function of the column, rather than on the column itself, we cannot use an index on the column to help with the sort. In other words, the sorting will be relatively slow. In the latter case, he recommends a solution similar to the one posted by @spanky (separate columns). A: If you'd like to support versions like 1.1-beta or using old MySql versions without INTE_ATON, you can get the same sort by splitting the version and sorting each part as an integer and string: SELECT version, REPLACE(SUBSTRING(SUBSTRING_INDEX(version, '.', 1), LENGTH(SUBSTRING_INDEX(version, '.', 1 - 1)) + 1), '.', '') v1, REPLACE(SUBSTRING(SUBSTRING_INDEX(version, '.', 2), LENGTH(SUBSTRING_INDEX(version, '.', 2 - 1)) + 1), '.', '') v2, REPLACE(SUBSTRING(SUBSTRING_INDEX(version, '.', 3), LENGTH(SUBSTRING_INDEX(version, '.', 3 - 1)) + 1), '.', '') v3, REPLACE(SUBSTRING(SUBSTRING_INDEX(version, '.', 4), LENGTH(SUBSTRING_INDEX(version, '.', 4 - 1)) + 1), '.', '') v4 FROM versions_table ORDER BY 0+v1, v1 DESC, 0+v2, v2 DESC, 0+v3, v3 DESC, 0+v4, v4 DESC; A: Use regular expressions. First normalize the value: SELECT REGEXP_REPLACE( REGEXP_REPLACE( REGEXP_REPLACE('v1.22.333', '^v', ''), '(^|\\.)(\\d+)', '\\100000\\2' ), '0+(\\d{5})(\\.|$)', '\\1\\2' ) Output: 00001.00022.00333 Then you can sort normally. This solution works with any number of components. You can scale component length from 5 to any fixed length.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How do I map lists of nested objects with Dapper I'm currently using Entity Framework for my db access but want to have a look at Dapper. I have classes like this: public class Course{ public string Title{get;set;} public IList<Location> Locations {get;set;} ... } public class Location{ public string Name {get;set;} ... } So one course can be taught at several locations. Entity Framework does the mapping for me so my Course object is populated with a list of locations. How would I go about this with Dapper, is it even possible or do I have to do it in several query steps? A: Sorry to be late to the party (like always). For me, it's easier to use a Dictionary, like Jeroen K did, in terms of performance and readability. Also, to avoid header multiplication across locations, I use Distinct() to remove potential dups: string query = @"SELECT c.*, l.* FROM Course c INNER JOIN Location l ON c.LocationId = l.Id"; using (SqlConnection conn = DB.getConnection()) { conn.Open(); var courseDictionary = new Dictionary<Guid, Course>(); var list = conn.Query<Course, Location, Course>( query, (course, location) => { if (!courseDictionary.TryGetValue(course.Id, out Course courseEntry)) { courseEntry = course; courseEntry.Locations = courseEntry.Locations ?? new List<Location>(); courseDictionary.Add(courseEntry.Id, courseEntry); } courseEntry.Locations.Add(location); return courseEntry; }, splitOn: "Id") .Distinct() .ToList(); return list; } A: Dapper is not a full blown ORM it does not handle magic generation of queries and such. For your particular example the following would probably work: Grab the courses: var courses = cnn.Query<Course>("select * from Courses where Category = 1 Order by CreationDate"); Grab the relevant mapping: var mappings = cnn.Query<CourseLocation>( "select * from CourseLocations where CourseId in @Ids", new {Ids = courses.Select(c => c.Id).Distinct()}); Grab the relevant locations var locations = cnn.Query<Location>( "select * from Locations where Id in @Ids", new {Ids = mappings.Select(m => m.LocationId).Distinct()} ); Map it all up Leaving this to the reader, you create a few maps and iterate through your courses populating with the locations. Caveat the in trick will work if you have less than 2100 lookups (Sql Server), if you have more you probably want to amend the query to select * from CourseLocations where CourseId in (select Id from Courses ... ) if that is the case you may as well yank all the results in one go using QueryMultiple A: Something is missing. If you do not specify each field from Locations in the SQL query, the object Location cannot be filled. Take a look: var lookup = new Dictionary<int, Course>() conn.Query<Course, Location, Course>(@" SELECT c.*, l.Name, l.otherField, l.secondField FROM Course c INNER JOIN Location l ON c.LocationId = l.Id ", (c, l) => { Course course; if (!lookup.TryGetValue(c.Id, out course)) { lookup.Add(c.Id, course = c); } if (course.Locations == null) course.Locations = new List<Location>(); course.Locations.Add(a); return course; }, ).AsQueryable(); var resultList = lookup.Values; Using l.* in the query, I had the list of locations but without data. A: No need for lookup Dictionary var coursesWithLocations = conn.Query<Course, Location, Course>(@" SELECT c.*, l.* FROM Course c INNER JOIN Location l ON c.LocationId = l.Id ", (course, location) => { course.Locations = course.Locations ?? new List<Location>(); course.Locations.Add(location); return course; }).AsQueryable(); A: I know I'm really late to this, but there is another option. You can use QueryMultiple here. Something like this: var results = cnn.QueryMultiple(@" SELECT * FROM Courses WHERE Category = 1 ORDER BY CreationDate ; SELECT A.* ,B.CourseId FROM Locations A INNER JOIN CourseLocations B ON A.LocationId = B.LocationId INNER JOIN Course C ON B.CourseId = B.CourseId AND C.Category = 1 "); var courses = results.Read<Course>(); var locations = results.Read<Location>(); //(Location will have that extra CourseId on it for the next part) foreach (var course in courses) { course.Locations = locations.Where(a => a.CourseId == course.CourseId).ToList(); } A: Alternatively, you can use one query with a lookup: var lookup = new Dictionary<int, Course>(); conn.Query<Course, Location, Course>(@" SELECT c.*, l.* FROM Course c INNER JOIN Location l ON c.LocationId = l.Id ", (c, l) => { Course course; if (!lookup.TryGetValue(c.Id, out course)) lookup.Add(c.Id, course = c); if (course.Locations == null) course.Locations = new List<Location>(); course.Locations.Add(l); /* Add locations to course */ return course; }).AsQueryable(); var resultList = lookup.Values; See here https://www.tritac.com/blog/dappernet-by-example/ A: Not sure if anybody needs it, but I have dynamic version of it without Model for quick & flexible coding. var lookup = new Dictionary<int, dynamic>(); conn.Query<dynamic, dynamic, dynamic>(@" SELECT A.*, B.* FROM Client A INNER JOIN Instance B ON A.ClientID = B.ClientID ", (A, B) => { // If dict has no key, allocate new obj // with another level of array if (!lookup.ContainsKey(A.ClientID)) { lookup[A.ClientID] = new { ClientID = A.ClientID, ClientName = A.Name, Instances = new List<dynamic>() }; } // Add each instance lookup[A.ClientID].Instances.Add(new { InstanceName = B.Name, BaseURL = B.BaseURL, WebAppPath = B.WebAppPath }); return lookup[A.ClientID]; }, splitOn: "ClientID,InstanceID").AsQueryable(); var resultList = lookup.Values; return resultList; A: There is another approach using the JSON result. Even though the accepted answer and others are well explained, I just thought about an another approach to get the result. Create a stored procedure or a select qry to return the result in json format. then Deserialize the the result object to required class format. please go through the sample code. using (var db = connection.OpenConnection()) { var results = await db.QueryAsync("your_sp_name",..); var result = results.FirstOrDefault(); string Json = result?.your_result_json_row; if (!string.IsNullOrEmpty(Json)) { List<Course> Courses= JsonConvert.DeserializeObject<List<Course>>(Json); } //map to your custom class and dto then return the result } This is an another thought process. Please review the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "158" }
Q: When running a sh file in linux, why do I have to run ./name.sh? I have a file called x.sh that I want to execute. If I run: x.sh then I get: x.sh: command not found If I run: ./x.sh then it runs correctly. Why do I have to type in ./ first? A: Because the current directory is normally not included in the default PATH, for security reasons: by NOT looking in the current directory all kinds of nastiness that could be caused by planting a malicious program with the name of a legitimate utility can be avoided. As an example, imagine someone manages to plant a script called ls in your directory, and that script executes rm *. If you wish to include the current directory in your path, and you're using bash as your default shell, you can add the path via your ~/.bashrc file. export PATH=$PATH:. Based on the explanation above, the risk posed by rogue programs is reduced by looking in . last, so all well known legitimate programs will be found before . is checked. You could also modify the systemwide settings via /etc/profile but that's probably not a good idea. A: Because the current directory is not into the PATH environment variable by default, and executables without a path qualification are searched only inside the directory specified by PATH. You can change this behavior by adding . to the end of PATH, but it's not common practice, you'll just get used to this UNIXism. The idea behind this is that, if executables were searched first inside the current directory, a malicious user could put inside his home directory an executable named e.g. ls or grep or some other commonly used command, tricking the administrator to use it, maybe with superuser powers. On the other hand, this problem is not much felt if you put . at the end of PATH, since in that case the system directories are searched first. But: our malicious user could still create his dangerous scripts named as common typos of often used commands, e.g. sl for ls (protip: bind it to Steam Locomotive and you won't be tricked anyway :D). So you see that it's still better to be safe that, if you type an executable name without a path qualification, you are sure you're running something from system directories (and thus supposedly safe). A: Because current directory is not in PATH (unlike cmd in Windows). It is a security feature so that malicious scripts in your current directory are not accidentally run. Though it is not advisable, to satisfy curiosity, you can add . to the PATH and then you will see that x.sh will work. A: If you don't explicitly specify a directory then the shell searches through the directories listed in your $PATH for the named executable. If your $PATH does not include . then the current directory is not searched. $ echo $PATH /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin This is on purpose. If the current directory were searched then the command you type could potentially change based on what directory you're in. This would allow a malicious user to place a binary named ls or cp into directories you frequent and trick you into running a different program. $ cat /tmp/ls rm -rf ~/* $ cd /tmp $ ls *kaboom* I strongly recommend you not add . to your $PATH. You will quickly get used to typing ./, it's no big deal. A: You can't execute your file by typing simply x.sh because the present working directory isn't in your $PATH. To see your present working directory, type $ pwd To see your $PATH, type $ echo $PATH To add the current directory to your $PATH for this session, type $ PATH=$PATH:. To add it permanently, edit the file .profile in your home directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How may I prevent the Designer changing control member modifiers to private? When in the Designer I change a property of a DataGridViewColumn on which I previously manually changed the modifier to public in the .Designer.cs file, the modifier gets reverted to private. Is there any way to prevent this? A: I would recommend not changing the designer. If you really need to have your controls public, I would recommend adding a property to expose them in your code file (not the designer file): public TextBox MyTextBox { get { return this.textBox1; } } This will provide public access to the designer generated types without worry of the designer overwriting your changes. It also makes it much more clear, in the long run, since your public API is defined in your main code file, and not in a second, designer generated file. That being said, in general, I'd avoid this. Instead of exposing the control itself, I would actually recommend exposing the data that you want to set. Take the text box above - If this text box was a title, I would expose that directly: public string Title { get { return this.textBoxTitle.Text; } set { this.textBoxTitle.Text = value; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7508344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need help improving query performance I need help with improving the performance of the following SQL query. The database design of this application is based on OLD mainframe entity designs. All the query does is returns a list of clients based on some search criteria: * *@Advisers: Only returns clients which was captured by this adviser. *@outlets: just ignore this one *@searchtext: (firstname, surname, suburb, policy number) any combination of that What I'm doing is creating a temporary table, then query all the tables involved, creating my own dataset, and then insert that dataset into a easily understandable table (@clients) This query takes 20 seconds to execute and currently only returns 7 rows! Screenshot of all table count can be found here: Table Record Count Any ideas where I can start to optimize this query? ALTER PROCEDURE [dbo].[spOP_SearchDashboard] @advisers varchar(1000), @outlets varchar(1000), @searchText varchar(1000) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Set the prefixes to search for (firstname, surname, suburb, policy number) DECLARE @splitSearchText varchar(1000) SET @splitSearchText = REPLACE(@searchText, ' ', ',') DECLARE @AdvisersListing TABLE ( adviser varchar(200) ) DECLARE @SearchParts TABLE ( prefix varchar(200) ) DECLARE @OutletListing TABLE ( outlet varchar(200) ) INSERT INTO @AdvisersListing(adviser) SELECT part as adviser FROM SplitString (@advisers, ',') INSERT INTO @SearchParts(prefix) SELECT part as prefix FROM SplitString (@splitSearchText, ',') INSERT INTO @OutletListing(outlet) SELECT part as outlet FROM SplitString (@outlets, ',') DECLARE @Clients TABLE ( source varchar(2), adviserId bigint, integratedId varchar(50), rfClientId bigint, ifClientId uniqueidentifier, title varchar(30), firstname varchar(100), surname varchar(100), address1 varchar(500), address2 varchar(500), suburb varchar(100), state varchar(100), postcode varchar(100), policyNumber varchar(100), lastAccess datetime, deleted bit ) INSERT INTO @Clients SELECT source, adviserId, integratedId, rfClientId, ifClientId, title, firstname, surname, address1, address2, suburb, state, postcode, policyNumber, max(lastAccess) as lastAccess, deleted FROM (SELECT DISTINCT 'RF' as Source, advRel.SourceEntityId as adviserId, cast(pe.entityId as varchar(50)) AS IntegratedID, pe.entityId AS rfClientId, cast(ifClient.Id as uniqueidentifier) as ifClientID, ISNULL(p.title, '') AS title, ISNULL(p.firstname, '') AS firstname, ISNULL(p.surname, '') AS surname, ISNULL(ct.address1, '') AS address1, ISNULL(ct.address2, '') AS address2, ISNULL(ct.suburb, '') AS suburb, ISNULL(ct.state, '') AS state, ISNULL(ct.postcode, '') AS postcode, ISNULL(contract.policyNumber,'') AS policyNumber, coalesce(pp.LastAccess, d_portfolio.dateCreated, pd.dateCreated) AS lastAccess, ISNULL(client.deleted, 0) as deleted FROM tbOP_Entity pe INNER JOIN tbOP_EntityRelationship advRel ON pe.EntityId = advRel.TargetEntityId AND advRel.RelationshipId = 39 LEFT OUTER JOIN tbOP_Data pd ON pe.EntityId = pd.entityId LEFT OUTER JOIN tbOP__Person p ON pd.DataId = p.DataId LEFT OUTER JOIN tbOP_EntityRelationship ctr ON pe.EntityId = ctr.SourceEntityId AND ctr.RelationshipId = 79 LEFT OUTER JOIN tbOP_Data ctd ON ctr.TargetEntityId = ctd.entityId LEFT OUTER JOIN tbOP__Contact ct ON ctd.DataId = ct.DataId LEFT OUTER JOIN tbOP_EntityRelationship ppr ON pe.EntityId = ppr.SourceEntityId AND ppr.RelationshipID = 113 LEFT OUTER JOIN tbOP_Data ppd ON ppr.TargetEntityId = ppd.EntityId LEFT OUTER JOIN tbOP__Portfolio pp ON ppd.DataId = pp.DataId LEFT OUTER JOIN tbOP_EntityRelationship er_policy ON ppd.EntityId = er_policy.SourceEntityId AND er_policy.RelationshipId = 3 LEFT OUTER JOIN tbOP_EntityRelationship er_contract ON er_policy.TargetEntityId = er_contract.SourceEntityId AND er_contract.RelationshipId = 119 LEFT OUTER JOIN tbOP_Data d_contract ON er_contract.TargetEntityId = d_contract.EntityId LEFT OUTER JOIN tbOP__Contract contract ON d_contract.DataId = contract.DataId LEFT JOIN tbOP_Data d_portfolio ON ppd.EntityId = d_portfolio.EntityId LEFT JOIN tbOP__Portfolio pt ON d_portfolio.DataId = pt.DataId LEFT JOIN tbIF_Clients ifClient on pe.entityId = ifClient.RFClientId LEFT JOIN tbOP__Client client on client.DataId = pd.DataId where p.surname <> '' AND (advRel.SourceEntityId IN (select adviser from @AdvisersListing) OR pp.outlet COLLATE SQL_Latin1_General_CP1_CI_AS in (select outlet from @OutletListing) ) ) as RFClients group by source, adviserId, integratedId, rfClientId, ifClientId, title, firstname, surname, address1, address2, suburb, state, postcode, policyNumber, deleted SELECT * FROM @Clients --THIS ONLY RETURNS 10 RECORDS WITH MY CURRENT DATASET END A: Clarifying questions What is the MAIN piece of data that you are querying on - advisers, search-text, outlets? It feels like your criteria allows for users to search in many different ways. A sproc will always use exactly the SAME plan for every question you ask of it. You get better performance by using several sprocs - each tuned for a specific search scenario (i.e I bet you could write something blazingly fast for querying just by policy-number). If you can separate your search-text into INDIVIDUAL parameters then you may be able to: * *Search for adviser relationships matching your supplied list - store in temp table (or table variable). *IF ANY surnames have been specified then delete all records from temp which aren't for people with your supplied names. *Repeat for other criteria lists - all the time reducing your temp records. *THEN join to the outer-join stuff and return the results. In your notes you say that outlets can be ignored. If this is true then taking them out would simplify your query. The "or" clause in your example means that SQL-Server needs to find ALL relationships for ALL portfolios before it can realistically get down to the business of filtering the results that you actually want. Breaking the query up Most of you query consists of outer-joins that are not involved in filtering. Try moving these joins into a separate select (i.e. AFTER you have applied all of your criteria). When SQL-Server sees lots of tables then it switches off some of its possible optimisations. So your first step (assuming that you always specify advisers) is just: SELECT advRel.SourceEntityId as adviserId, advRel.TargetEntityId AS rfClientId INTO #temp1 FROM @AdvisersListing advisers INNER JOIN tbOP_EntityRelationship advRel ON advRel.SourceEntityId = advisers.adviser AND advRel.RelationshipId = 39; The link to tbOP_Entity (aliased as "pe") does not look like it is needed for its data. So you should be able to replace all references to "pe.EntityId" with "advRel.TargetEntityId". The DISTINCT clause and the GROUP-BY are probably trying to achieve the same thing - and both of them are really expensive. Normally you find ONE of these used when a previous developer has not been able to get his results right. Get rid of them - check your results - if you get duplicates then try to filter the duplicates out. You may need ONE of them if you have temporal data - you definitely don't need both. Indexes Make sure that the @AdvisersListing.adviser column is same datetype as SourceEntityId and that SourceEntityId is indexed. If the column has a different datatype then SQL-Server won't want to use the index (so you would want to change the data-type on @AdvisersListing). The tbOP_EntityRelationship tables sounds like it should have an index something like: CREATE UNIQUE INDEX advRel_idx1 ON tbOP_EntityRelationship (SourceEntityId, RelationshipId, TargetEntityId); If this exists then SQL-Server should be able to get everything it needs by ONLY going to the index pages (rather than to the table pages). This is known as a "covering" index. There should be a slightly different index on tbOP_Data (assuming it has a clustered primary key on DataId): CREATE INDEX tbOP_Data_idx1 ON tbOP_Data (entityId) INCLUDE (dateCreated); SQL-Server will store the keys from the table's clustered index (which I assume will be DataId) along with the value of "dateCreated" in the index leaf pages. So again we have a "covering" index. Most of the other tables (tbOP__Client, etc) should have indexes on DataId. Query plan Unfortunately I couldn't see the explain-plan picture (our firewall ate it). However 1 useful tip is to hover your mouse over some of the join lines. It tells you how many records be accessed. Watch out for full-table-scans. If SQL-Server needs to use them then its pretty-much given up on your indexes. Database structure Its been designed as a transaction database. The level of normalization (and all of the EntityRelationship-this and Data-that are really painful for reporting). You really need to consider having a separate reporting database that unravels some of this information into a more usable structure. If you are running reports directly against your production database then I would expect a bunch of locking problems and resource contention. Hope this has been useful - its the first time I've posted here. Has been ages since I last tuned a query in my current company (they have a bunch of stern-faced DBAs for sorting this sort of thing out). A: Looking at your execution plan... 97% of the cost of your query is in processing the DISTINCT clause. I'm not sure it is even necessary since you are taking all that data and doing a group by on it anyway. You might want to take it out and see how that affects the plan. A: That kind of query is just going to take time, with that many joins and that many temp tables, there's just nothing easy or efficient about it. One trick I have been using is using local variables. It might not be an all out solution, bit if it shaves a few seconds, it's worth it. DECLARE @Xadvisers varchar(1000) DECLARE @Xoutlets varchar(1000) DECLARE @XsearchText varchar(1000) SET @Xadvisers = @advisers SET @Xoutlets = @outlets SET @XsearchText = @searchText Believe me, I have tested it thoroughly, and it helps with complicated scripts. Something about the way SQL Server handles local variables. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7508345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Memory allocation operators and expressions In C++, is 'new' an operator or an expression or some kind of keyword? a similar question that comes in mind is, should i call '=' an operator or expression? A: C++ separates the notion of memory allocation and object lifetime. This is a new feature compared to C, since in C an object was equivalent to its memory representation (which is called "POD" in C++). An object begins its life when a constructor has completed, and its life ends when the destructor has completed. For an object of dynamic storage duration, the life cycle thus consists of four key milestones: * *Memory allocation. *Object construction. *Object destruction. *Memory deallocation. The standard way in C++ to allocate memory dynamically is with the global ::operator new(), and deallocation with ::operator delete(). However, to construct an object there is only one method: A new expression: T * p = new T; This most common form of the new expression does allocation and construction in one step. It is equivalent to the broken down version: void * addr = ::operator new(sizeof(T)); T * p = new (addr) T; // placement-new Similarly, the delete expression delete p; first calls the destructor and then releases memory. It is equivalent to this: p->~T(); ::operator delete(addr); Thus, the default new and delete expressions perform memory allocation and object construction in one wash. All other forms of the new expression, collectively called "placement new", call a corresponding placement-new operator to allocate memory before constructing the object. However, there is no matching "placement delete expression", and all dynamic objects created with placement-new have to be destroyed manually with p->~T();. In summary, it is very important to distinguish the new expression from the operator new. This is really at the heart of memory management in C++. A: It's all of those. 2.13 Table 4 explicitly lists new as a keyword. 5.3.4 Introduces the new-expression. This is an expression such as new int(5) which uses the new keyword, a type and an initial value. 5.3.4/8 Then states that operator new is called to allocate memory for the object created by the new-expression = works quite the same. Each class has an operator= (unless explicitly deleted), which is used in assignment expressions. We usually call a=5; just an assignment, even when it's technically "an expression statement containing an assignment expression." A: new is operator. You can overload it and write your own version of it. Also I think that = is operator. Expression is more complex thing which consist of operators, variables, function calls etc. And please try to get C++ language standard. It must describe all things you mentioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MOSS 2010 virtual path to ASP.NET I am attempting to host an ASP.NET application inside of my SharePoint site. I want to host a full-application so I'm hoping to run it as a virtual path application. Following instructions mentioned in other areas around the web, which said that I could go into ISS and create a virtual path inside of my SharePoint site to run the application. Link (page 4) After finishing this portion I began getting asked for credentials. I got rid of the credentials request, by browsing to the folder containing my Virtual Path and changing security settings to allow iUSR_ account. I no longer get credentials, but I now get a blank page. I don't know how to get passed this blank page issue, any help is greatly appreciated. Background: I realize that I can run an application in the layouts folder, but it doesn't seem to work the same as it references .cs files that should be in the code-behind. -Update- The blank page issue is solved if I convert the virtual path to an application. However, it seems that I can't piggy-back off of the SharePoint's user credentials when it's an application. A: Have you checked that the AppPool for the MVC site is running as the same user as the sharepoint webapp?
{ "language": "en", "url": "https://stackoverflow.com/questions/7508347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: (PHP) $_POST + cURL + multi array I try to send a multi array via cURL but I can't find a nice way to do it. My code example: $data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); This will work and give the result I want on the curl_init() site: print_r( $_POST ) : Array ( [a] => testa [b] => testb [c] => Array ( [d] => test1 [e] => test2 ) ) I'd like to add the c array dynamically like: $c['d'] = 'test1'; $c['e'] = 'test2'; But if I try to add an array with array_push or [] I always get and (string)Array in the Array without data. Can anyone help me to do it? The whole code for faster testing: $url = 'url_to_test.php'; $data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' ); $ch = curl_init($url); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $buffer = curl_exec ($ch); curl_close ($ch); echo $buffer; The test.php print_r($_POST); Thanks for any help! cheers A: In $data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' ) You've simply added new string keys "c[d]" and "c[e]". If you want a nested array, use: $data = array( 'a' => 'testa', 'b' => 'testb', 'c' => array( 'd' => 'test1', 'e' => 'test2' ) ) -- EDIT -- You're trying to set POST data, which is essentially a set of key value pairs. You can't provide a nested array. You could, however, serialize the nested array and decode it at the other end. Eg: $post_data = array('data' => serialize($data)); And at the receiving end: $data = unserialize($_POST['data']); A: here is your solution $urltopost = "http://example.com/webservice/service.php"; $datatopost = array (0 =>array('a'=>'b','c'=>'d'),1 =>array('a'=>'b','c'=>'d'),2 =>array('a'=>'b','c'=>'d'),3 =>array('a'=>'b','c'=>'d')); $post_data = array('data' => serialize($datatopost)); $ch = curl_init ($urltopost); curl_setopt ($ch, CURLOPT_POST, true); curl_setopt ($ch, CURLOPT_POSTFIELDS,$post_data); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); $returndata = curl_exec ($ch); echo "<pre>"; print_r(unserialize($returndata)); service.php code $temp = unserialize($_POST['data']); echo serialize($temp);
{ "language": "en", "url": "https://stackoverflow.com/questions/7508349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert delimited string into array key path and assign value I have a string like this: $string = 'one/two/three/four'; which I turn it into a array: $keys = explode('/', $string); This array can have any number of elements, like 1, 2, 5 etc. How can I assign a certain value to a multidimensional array, but use the $keys I created above to identify the position where to insert? Like: $arr['one']['two']['three']['four'] = 'value'; Sorry if the question is confusing, but I don't know how to explain it better A: $string = 'one/two/three/four'; $keys = explode('/', $string); $arr = array(); // some big array with lots of dimensions $ref = &$arr; while ($key = array_shift($keys)) { $ref = &$ref[$key]; } $ref = 'value'; What this is doing: * *Using a variable, $ref, to keep track of a reference to the current dimension of $arr. *Looping through $keys one at a time, referencing the $key element of the current reference. *Setting the value to the final reference. A: This is kind of non-trivial because you want to nest, but it should go something like: function insert_using_keys($arr, $keys, $value){ // we're modifying a copy of $arr, but here // we obtain a reference to it. we move the // reference in order to set the values. $a = &$arr; while( count($keys) > 0 ){ // get next first key $k = array_shift($keys); // if $a isn't an array already, make it one if(!is_array($a)){ $a = array(); } // move the reference deeper $a = &$a[$k]; } $a = $value; // return a copy of $arr with the value set return $arr; } A: You'll need to first make sure the key's exist, then assign the value. Something like this should work (untested): function addValueByNestedKey(&$array, $keys, $value) { $branch = &$array; $key = array_shift($keys); // add keys, maintaining reference to latest branch: while(count($keys)) { $key = array_pop($keys); if(!array_key_exists($key, $branch) { $branch[$key] = array(); } $branch = &$branch[$key]; } $branch[$key] = $value; } // usage: $arr = array(); $keys = explode('/', 'one/two/three/four'); addValueByNestedKey($arr, $keys, 'value'); A: it's corny but: function setValueByArrayKeys($array_keys, &$multi, $value) { $m = &$multi foreach ($array_keys as $k){ $m = &$m[$k]; } $m = $value; } A: $arr['one']['two']['three']['four'] = 'value'; $string = 'one/two/three/four'; $ExpCheck = explode("/", $string); $CheckVal = $arr; foreach($ExpCheck AS $eVal){ $CheckVal = $CheckVal[$eVal]??false; if (!$CheckVal) break; } if ($CheckVal) { $val =$CheckVal; } this will give u your value in array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Problems with php.ini My problem is related to the php.ini file I think, but it might be something else. Let's say we have a site architecture where inside the root directory there is another directory named img and a file named index.php. Inside the directory img there is a file named image.jpg. So in index.php, to refer to an image, I would use /img/image.jpg. My question is, what should I change in php.ini to be able to write img/image.jpg instead of /img/image.jpg. Thanks A: Relative paths get resolved by the web browser, not by PHP. There is no way to override this behavior on the web server. A: Nothing PHP can do. You could essentially do that with Apache rewrites but it makes much more sense to just use absolute paths. You should not try to mix absolute and relative paths because it will only cause problems for you in the future. What's wrong with adding the '/' to the front of the path? Not only that, but it will confuse the hell out of people trying to debug your code that all of your relative paths are becoming absolute paths in Apache. A: My question is, what should I change in php.ini to be able to write img/image.jpg instead of /img/image.jpg. This is answering your question but not the answer you would like to hear. It quite simple, let's first list the ini settings: * *auto_prepend_file (probably in conjunction with include_path) And that's all. How it works: Prepend a php script with the ini directive. inside that file, you start output buffering with your own callback function: function callback($buffer) { // slash that image that you want to write without slash return (str_replace("img/image.jpg", "/img/image.jpg", $buffer)); } ob_start("callback"); You are now able to write img/image.jpg instead of /img/image.jpg because your output filter function does re-write it for you. But take care that you're not trying to fix the wrong end with this. General rule of hypertext references apply, see Uniform Resource Identifier (URI): Generic Syntax , Hypertext Transfer Protocol -- HTTP/1.1 and Hypertext Markup Language - 2.0 .
{ "language": "en", "url": "https://stackoverflow.com/questions/7508354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom Control switching between two styles I'm making a custom control which has two very different styling needs. One for a basic look, and another for a more advanced look. My control contains a dependency property for the following enum: public enum ControlTypes { Basic, Advanced } I created two styles in the generic.xaml (with very different templates), and gave each a key. Inside the change handler for the enum property I'm trying to find the styles and set the correct one. private static void OnControlTypePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var myCustomControl = (MyCustomControl)d; var basicControlStyle = Application.Current.TryFindResource("BasicControlStyle") as Style; var advancedControlStyle = Application.Current.TryFindResource("AdvancedControlStyle") as Style; if (myCustomControl.ControlType == ControlTypes.Basic) myCustomControl.Style = basicControlStyle; else if (myCustomControl.ControlType == ControlTypes.Advanced) myCustomControl.Style = advancedControlStyle; } The two styles are always null. I'm not sure how to get the styles from inside the generic.xaml. Or is there a better way to swap my styles? A: Delete the code in OnControlTypePropertyChanged and put something like this in your XAML. Note that I have bound to a property called IsAdvanced because it was simpler for testing but you can bind to an enum by changing the "True" for {x:Static namespace:nameofyourenum.Value} <Style TargetType="local:SomeControl"> <Style.Setters> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate TargetType="local:SomeControl"> <StackPanel> <TextBlock Text="DefaultTemplate"></TextBlock> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style.Setters> <Style.Triggers> <Trigger Property="IsAdvanced" Value="True"> <Trigger.Setters> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate TargetType="local:SomeControl"> <TextBlock Text="Advanced Template"></TextBlock> </ControlTemplate> </Setter.Value> </Setter> </Trigger.Setters> </Trigger> </Style.Triggers> </Style> Note that this still give the programmer who uses your control the ability to completely override the control template and do what they want. Your original approach didn't allow this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: select max element columns from group I'd like to select the maximum row of a group, but I'd like the query to return the other columns from that row. I know how MAX() can return the greatest integer in the group, but I don't know how to get the other columns for the max result. In this example, I'd like to have a query that selects the maximum userId from each group but returns the userId and Name Users groupId | userId | name ---------------------- 1 | 1 | mike 1 | 2 | dave 2 | 3 | bill 2 | 4 | steve I'd like the output of the query to be groupId | userId | name ----------------------- 1 | 2 | dave 2 | 4 | steve I know I could do select groupId, max(userId) from Users group by groupId; and then do a subquery again on users. I'm just looking to see if there is a better way. If it matters, I'm using MySQL A: Try this select * from users join (select groupId, max(userId) as maxU from Users group by groupId) xx on xx.groupId=users.groupId and users.userId=xx.maxU
{ "language": "en", "url": "https://stackoverflow.com/questions/7508361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recommended sender name when sharing an address We have an application that is used for client management, which has a generic e-mail account attached to it (info@example.com). All e-mail that is sent here, is received by our application (processed using PHP). Mail will be replied by various employees, depending on the issue. So sometimes John answers, and sometimes Peter. Currently, the "Sender" header of the mail will be set to: Company Name / John Company Name / Peter etc. That allows people to see who they are communicating with, we figured. However, it turns out that some e-mail clients by default do not show you the address that is used to send the mail once you have added this to the address book (often also done automatically when replying). So this means that if John sends from info@example.com, the mail header will say "Company Name / John", but the email client says "Company name / Peter", because the client was in touch with Peter before. The simple solution is to only put "Company Name" as sender, but I prefer not to lose this detail. So I was wondering if others have had the same issue, and perhaps know other tricks. Thanks! A: Tell Peter and John not to reply the original email, and send a new one from their respective account with a copy of the original message.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Boost libs building - difference between runtime-link and link options I'm trying to build boost libraries in Windows 7 with MSVC (VS 2010). I have come across the options runtime-link and link in the bjam command line options. I would like to know how they are used and what is the exact difference between them. I have built the Boost Regex library using this command line bjam --with-regex variant=release --build-options=complete it produced these files: 1)boost_regex-vc100-mt-1_47.dll (Import library:boost_regex-vc100-mt-1_47.lib) 2)libboost_regex-vc100-mt-1_47.lib 3)libboost_regex-vc100-mt-s-1_47.lib 4)libboost_regex-vc100-s-1_47.lib What is the difference between 2 and 3 .lib files? Both of them are static libs. I have gone through the Boost doc but didn't find much explanation in that. TIA A: runtime-link refers to how your compiler's runtime is linked. That is, it corresponds to VC's Multithreaded vs. Multithreaded DLL option. Runtime means the components required for using the standard libraries available with your compiler. You have probably seen the dynamic link files at some point: MSVCRTXX.DLL (C runtime) and MSVCPXX.DLL (C++ standard library), MFCXX.DLL (MFC core classes). The static counterparts are LIBC and LICBP (see here for the library table) The runtime-link option you use when building Boost should match the option when you're using for your client code. Otherwise you'll get errors due to mismatched runtime either at link time or upon running your program. When building your program to use the dynamic link runtime, you need to include the VC redistributable when deploying your application. link refers to how the boost library your building will be linked to, either as a static or dynamic link library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Perl5.12 not installing via Macports When trying to install Imagemagick via Macports, I keep getting an error when it goes to build the perl5.12 dependancy. It says: Error: Status 1 encountered during processing. I’ve tried updating Macports, installing/building perl5.12 independently, uninstalling and reinstalling perl5.12 to no avail. Here’s what error part of the log says: Making x2p stuff :info:build ./perl -f -Ilib pod/buildtoc --build-toc -q :info:build make[1]: Entering directory `/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_lang_perl5.12/perl5.12/work/perl-5.12.3/x2p' :info:build You haven't done a "make depend" yet! :info:build make[1]: *** [hash.o] Error 1 :info:build make[1]: Leaving directory `/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_lang_perl5.12/perl5.12/work/perl-5.12.3/x2p' :info:build make: *** [translators] Error 2 :info:build make: *** Waiting for unfinished jobs.... :info:build make: Leaving directory `/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_lang_perl5.12/perl5.12/work/perl-5.12.3' :info:build shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_lang_perl5.12/perl5.12/work/perl-5.12.3" && /usr/bin/make -j2 -w all " returned error 2 :error:build Target org.macports.build returned: shell command failed (see log for details) :debug:build Backtrace: shell command failed (see log for details) while executing "command_exec build" (procedure "portbuild::build_main" line 8) invoked from within "$procedure $targetname" :info:build Warning: the following items did not execute (for perl5.12): org.macports.activate org.macports.build org.macports.destroot org.macports.install :error:build Failed to install perl5.12 :debug:build couldn't open "/System/Library/Frameworks/Tcl.framework/Versions/8.5/Resources/tclIndex": no such file or directory while executing "open [file join $dir tclIndex]" :notice:build Log for perl5.12 is at: /opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_lang_perl5.12/perl5.12/main.log Here’s the whole log. Does anybody know what’s going on or what I’m doing wrong? A: Turns out that latest macPorts update fixed my issue, just had to run selfupdate. A: What version of Mac OS X do you have? I have Lion, and it comes with Perl 5.12.3. You may need to install the developer tools. You can always try ActivePerl which is version 5.12.4. I haven't tried ActivePerl on the Mac, but if you have the developer tools installed, you'll have the required gcc compiler and make installed, so you can install the XS CPAN packages. On the PC, you have to install CPAN from the Perl Package Manager and not all CPAN modules will install, but I don't know if you have the same issues with ActivePerl on the Mac since the Mac is a Unix operating system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why isn't this loop vectorized? One particular hot spot when I profile a code I am working on, is the following loop: for(int loc = start; loc<end; ++loc) y[loc]+=a[offset+loc]*x[loc+d]; where the arrays y, a, and x have no overlap. It seems to me that a loop like this should be easily vectorized, however when I compile using g++ with the options "-O3 -ftree-vectorize -ftree-vectorizer-verbose=1", I get no indication that this particular loop was vectorized. However, a loop occurring just before the code above: for(int i=0; i<m; ++i) y[i]=0; does get vectorized according to the output. Any thoughts on why the first loop is not vectorized, or how I might be able to fix this? (I am not all that educated on the concept of vectorization, so I am likely missing something quite obvious) As per Oli's suggestion, turning up the verbosity yields the following notes (while I am usually good at reading compiler warnings/errors/output, I have no idea what this means): ./include/mv_ops.h:89: note: dependence distance = 0. ./include/mv_ops.h:89: note: accesses have the same alignment. ./include/mv_ops.h:89: note: dependence distance modulo vf == 0 between *D.50620_89 and *D.50620_89 ./include/mv_ops.h:89: note: not vectorized: can't determine dependence between *D.50623_98 and *D.50620_89 A: You need to tell the compiler that x, y, and a do not overlap. In C/C++ terms that means telling the compiler that those pointers do not alias by declaring them with restrict (or __restrict). gcc is very aggressive about optimizations when it assumes no aliasing, so be careful. A: One possibility is that the compiler can't guarantee that there are no aliases. In other words, how can the compiler be sure that y, a and x don't overlap in some way? If you turn the verbosity level up, you may get some extra info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ubuntu: Redirection from a .txt file in Java This should be pretty simple but for some reason, I can't get this program to take arguments from a .txt file and output it. Here's my code: public class Lab2 { static Scanner input = new Scanner(System.in); public static void main(String[] args) { Lab2_CLA.Lab2_CLA(args); } } public class Lab2_CLA { public static void Lab2_CLA(String[] data) { System.out.printf("%s, %s: %s%n", data[1], data[0], data[2]); } } I compiled the code and it works if I give it arguments through the terminal. Ex: Typing "java lab2/Lab2 John Doe 12345678" Prints out: "Doe, John: 12345678" However, how can I get it to read data from a .txt file by typing the following into the terminal: "java lab2/Lab2 < input.txt"? Whenever I do this, I get the following error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at lab2.Lab2_CLA.Lab2_CLA(Lab2_CLA.java:12) at lab2.Lab2.main(Lab2.java:34) A: Input redirection sends the file to the program's stdin (standard input file), not in its command line parameters. On a Unix-alike you can obtain the effect you want by using the backtick operator: java lab2/Lab2 `cat input.txt` In short, the text between the backticks is executed, and the result of the execution will be inserted in its place. EDIT (responding to OP's edit): You get an out of bounds exception because with the redirection the program doesn't get any command line parameters, yet hard-address elements 0 1 and 2 of the args array. Should for some reason the backtick based solution not be possible for you the only option will be to modify your program to either read its stdin (technique show here Java file input as command line argument), or accept a filename as an argument, and read that file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableView how to change color? How would I change the color of a UITableView? Or change the color of a cell? Or change the color of the navigation bar at the top? (iOS) A: You can change the color of a cell in the UITableView delegate method like this: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; if (!cell) { cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"]autorelease]; } } //Here you can change de color/background of your cell with anything you want //Change the color: [cell setBackgroundColor:[UIColor blackColor]]; //Change the background image of a cell: UIImage *theImage = [UIImage imageNamed:@"ximage.png"]; [[cell imageView] setImage:theImage]; } A: To change the color of a cell you need to create your own subclass of UITableViewCell. And to change the background color of the nav bar, I believe it is self.navigationItem.backgroundColor = [UIColor redColor]; Thanks, macintosh264 A: You can do so by setting the backgroundView to the table and the contentView's backgroundColor of a cell. See this to get started with. The navigation bar can be done by subclassing the UINavigationBar and overriding the drawRect method. P.S: All of the above are basic topics on which tutorials are littered all over the web and Stack Overflow itself. Try searching and reading up. A: note that as of ios3 you don't set the cell background color in * *(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath you set it in * *(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath as noted here http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7508384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: (Qt Creator - Cpp Based Application) Q VS using Pointers? here is my code: //MainWindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGui> class MainWindow : public QWidget { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); private: QTextEdit *textEdit; }; #endif // MAINWINDOW_H // MainWindow.cpp #include "mainwindow.h" #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) { textEdit = new QTextEdit(); } MainWindow::~MainWindow() { delete textEdit; } //main.cpp #include <QtGui> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } Is it more efficient (here's the "Q[Objects] VS using Pointers?" part of the question) to: 1) Use pointers as I am actually doing or 2) Use objects (removing * + delete statement) Thank you! A: MainWindow::MainWindow(QWidget *parent) { textEdit = new QTextEdit(this); } MainWindow::~MainWindow() { } A: For QObject members as pointers, you shouldn't use delete, the QTextEdit will probably be a child of MainWindow, so it will be deleted automatically. It would, of course, be theoretically faster to use non-pointer QObject members, with one less level of indirection. Like this (for those who didn't understand the question): class MainWindow : public QMainWindow { ... private: QTextEdit textEdit; }; and there is also less code to type, because you don't have to retype the class name of the members to initialize them in the constructor. But since QObject are themselves already heavily using indirection (with their d-pointer), the gain will probably be negligible. And the extra code you type with pointer members allows you to have a lower coupling between your header files and Qt, because you can use forward declarations instead of header inclusion, which means faster compilations (especially if you are not using precompiled headers yet) and recompilations. Also, * *manually deleting QObject pointer members, or *declaring QObject as non-pointers members can causes double deletion, if you don't respectively delete/declare them in the right order (children then parents for deletion, or parents then children for declaration). For example: class MainWindow : public QMainWindow { ... private: QTextEdit textEdit; QScrollArea scrollArea; }; MainWindow::MainWindow() { setCentralWidget(&scrollArea); QWidget *scrolledWidget = new QWidget(&scrollArea); QVBoxLayout *lay = new QVBoxLayout(scrolledWidget); lay->addWidget(...); lay->addWidget(&textEdit); // textEdit becomes a grand-child of scrollArea scrollArea.setWidget(scrolledWidget); } When MainWindow is deleted, its non-static class members are deleted in the reverse order of their declaration in the class. So scrollArea is destroyed first then textEdit, but scrollArea also destroys its children including textEdit, so textEdit is effectively destroyed twice causing a crash. So it is less error prone to use QObject members as pointers, and to not delete the QObject which have a parent yourself. A: Try creating QLineEdit on the stack and then put it into layout... Quit your application... What do you see? HINT: launch your application in debugger. ksming is right about reading documentation. It is not language specific issue. If you are asking what is faster: heap or stack allocation then form your question properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: File I/O in c++ and linux command line redirect I've got a program that accepts a text file with a map on it, then finds the shortest path and outputs that to another file. it needs to work like this ./pathFinder -arg < inputMap.txt > outputMap.txt My question is, with this input, what would get filled into argv[] and argc (do the redirects count as arguments), and also should I use file streams or just cin/cout... or maybe something else. Thanks. A: argc will be 2, and argv[1] will point to "-arg". Redirects will simply appear on stdin and stdout (wrapped by std::cin and std::cout). A: argv will contain {"./pathFinder", "-arg"} A: The redirect will not count as arguments. Just use cin/cout will be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Primes in PHP, elliptic curve how i can calculate receiving a number K, K return the next prime number greater than 2 ^ 57 + 1 ? some 1 can help me with that ? A: If you need prime tester, you can download it here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Draw a circle in WPF using min(width, height)/2 as radius How I can draw a circle in WPF (without code-behind) using min(width, height)/2 as radius? A: Where does width and height come from? Example XAML for a circle is: <Canvas Background="LightGray"> <Ellipse Canvas.Top="50" Canvas.Left="50" Fill="#FFFFFF00" Height="75" Width="75" StrokeThickness="5" Stroke="#FF0000FF"/> </Canvas> A circle is just an Ellipse where Height = Width. A: you can do it in pure XAML you just need to use Binding for the values. You also have to make sure that everything is named <Grid Name="grdMain"> <Grid.ColumnDefinitions> <ColumnDefinition Width="75" Name="Col1" /> <ColumnDefinition Width="100" Name="Col2" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="75" Name="Row1" /> <RowDefinition Height="100" Name="Row2" /> </Grid.RowDefinitions> <Ellipse Grid.Column="1" Grid.Row="1" Canvas.Top="50" Canvas.Left="50" Fill="#FFFFFF00" Height="{Binding RowDefinitions/ActualHeight, ElementName=Row1, Mode=OneWay}" Width="{Binding ColumnDefinitions/ActualWidth, ElementName=Col1, Mode=OneWay}" StrokeThickness="5" Stroke="#FF0000FF"/> </Grid>
{ "language": "en", "url": "https://stackoverflow.com/questions/7508398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Arithmetic overflow error converting varchar to data type numeric? SELECT CASE Price WHEN '' THEN 0.0 ELSE Price END FROM Table If price empty, it returns 0.0 but if column has value it gives me the error below Arithmetic overflow error converting varchar to data type numeric. How to change my code to handle this case? A: SELECT CASE Price WHEN '' THEN 0.0 ELSE CAST(Price AS DECIMAL(...)) END FROM Table Implicit conversions will often take the smallest type possible, so when you hit a larger value it will fail. Explicitly convert/cast your value to the right type in your CASE/ELSE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: float [] array problem in objective c I am coding in xcode by objective c. I came up with a problem. I want to try like declare float[] weights; results looks like this weight[0] = 0.5 weight[1] = 0.4 weight[2] = 0.9 A.h NSMutableArray *weight; A.m weights = [NSMutableArray array]; for(int i=0; i < 4; i++) { float randomNumber = arc4random() % 11; [weights addObject:[[NSNumber alloc] initWithFloat:randomNumber]]; NSLog(@" for loops color prob weghts=%f",[weights objectAtIndex:i] ); } I don't know what is wrong with this code. Please help me to find out? When I print it by NSLOG " all [weight = 0.000] and also How do I access like [weight floatvalue]. secondly, when I create this class to another class there are weight [0],[1],[2],[3] and no values A: It should be [[weights objectAtIndex:i] floatValue] when you print it in your NSLog A: NSNumber is a class, not a integral type. Therefore, you must use %@, not %f. NSLog(@" for loops color prob weghts=%@",[weights objectAtIndex:i] ); Alternatively, use floatValue, like you said. You may need to cast the object into NSNumber first (for type safety) NSNumber *number = (NSNumber *)[weights objectAtIndex:i]; NSLog(@" for loops color prob weghts=%f", [number floatValue]); Also, you are leaking objects here, because you did not release them after putting them in the array. Either release after placing them in array, or use [NSNumber numberWithFloat:]
{ "language": "en", "url": "https://stackoverflow.com/questions/7508400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving array values from within a class Working on my first OOP app and I am having some trouble accessing the values of an array returned by a public function within my class. Here is the function - //Process new transaction public function addTransaction($amount, $payee, $category, $date, $notes) { global $db; //Check to see if payee exists in Payee table $checkPayee = $db->prepare("SELECT * FROM payees WHERE name = ?"); $checkPayee->execute(array($payee)); $checkPayeeNum = $checkPayee->fetchColumn(); $payeeDetails = $checkPayee->fetch(); if ($checkPayeeNum < 1) { $insertPayee = $db->prepare("INSERT INTO payees (name, cat) VALUES(?, ?)"); $insertPayee->execute(array($payee, $cat)); } else { if ($payeeDetails['cat'] == "") { $updatePayee = $db->prepare("UPDATE payees SET cat=? WHERE name=?"); $updatePayee->execute(array($cat, $payee)); } } //Process the transaction $proc = $db->prepare("INSERT INTO transactions (amount, payee, cat, date, notes) VALUES (?, ?, ?, ?, ?)"); $proc->execute(array($amount, $payee, $cat, $date, $notes)); //Prepare array for JSON output $todaysTrans = $this->fetchDailyTotal(); $weeklyTotal = $this->fetchWeeklyTotal(); $accountBalance = $this->balanceAccount(); $jsonOutput = array("dailyTotal" => $todaysTrans, "weeklyTotal" => $weeklyTotal, "accountBalance" => $accountBalance); return $jsonOutput; } Instantiating the object is not the issue, trying to figure out how to access the $jsonOutput array. How would one accomplish this? Thanks! A: // In some other PHP file... include 'YourClass.php'; $yourObject = new YourClass(); $returnedArray = $yourObject->addTransaction(...); // Access the returned array values echo 'Daily Total: ', $returnedArray['dailyTotal'], "\n"; echo 'Weekly Total: ', $returnedArray['weeklyTotal'], "\n"; echo 'Account Balance: ', $returnedArray['accountBalance'], "\n"; Also, for what it's worth, it's very confusing for you to be returning a PHP array called $jsonOutput, as it's not JSON encoded, which is what most developers will expect it to be. If you're wanting it to be JSON encoded, use json_encode() (see here for more info).
{ "language": "en", "url": "https://stackoverflow.com/questions/7508402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Magento custom module for exporting order data to external database I've created a custom module in Magento that we'll use to pass along name and product info to an external database. These variables need to be passed to the external database after the order is submitted. Here's what I have so far (three files): This is the config.xml file, which is located in the following directory: app/code/local/Companyname/Modhere/etc/ <?xml version="1.0"?> <config> <global> <models> <Companyname_Modhere> <class>Exp_Data_Model</class> </Companyname_Modhere> </models> <events> <sales_order_payment_pay> <observers> <companyname_modhere_observer> <type>singleton</type> <class>Exp_Data_Model_Order_Observer</class> <method>external_notification_trigger</method> </companyname_modhere_observer> </observers> </sales_order_payment_pay> </events> </global> </config> This is the Companyname_Modhere.xml file, which is located in the following directory: app/etc/modules/ <?xml version="1.0"?> <config> <modules> <Companyname_Modhere> <codePool>local</codePool> <active>true</active> </Companyname_Modhere> </modules> </config> This is the Observer.php file, and where I'm having trouble. It's located in the following directory: app/code/local/Companyname/Modhere/Model/ <?php class Exp_Data_Model_Order_Observer { public function __construct() { } public function external_notification_trigger($observer) { $orderId = $observer->getPayment()->getOrder()->getId(); $orderNumber = $observer->getPayment()->getOrder()->getIncrementId(); return $this; } } I need this module to save the firstname, lastname, quantity, and productname, so that it can be passed along to the other database. Am I on the right track? A: I've cleaned up your example for you. You were missing a 'version' element and you had the class names mis-matching the module name. This still isn't 100%, but it should get you much closer and hopefully fix the observer problem you were having. /app/etc/modules/Companyname_Modhere.xml <?xml version="1.0"?> <config> <modules> <Companyname_Modhere> <codePool>local</codePool> <active>true</active> <depends> <Mage_Core /> <Mage_Sales /> </depends> </Companyname_Modhere> </modules> </config> /app/code/local/Companyname/Modhere/etc/config.xml <?xml version="1.0"?> <config> <modules> <version>1.0.0</version> </modules> <global> <models> <Companyname_Modhere> <class>Companyname_Modhere_Model</class> </Companyname_Modhere> </models> <events> <sales_order_payment_pay> <observers> <Companyname_Modhere> <type>singleton</type> <class>Companyname_Modhere/Observer</class> <method>orderPaid</method> </Companyname_Modhere> </observers> </sales_order_payment_pay> </events> </global> </config> /app/code/local/Companyname/Modhere/Model/Observer.php <?php class Companyname_Modhere_Model_Observer { public function orderPaid(Varien_Event_Observer $observer) { $order = $observer->getPayment()->getOrder(); $data = array(); $data['id'] = $order->getIncrementId(); $data['first_name'] = $order->getCustomerFirstname(); $data['last_name'] = $order->getCustomerLastname(); $data['items'] = array(); foreach ($order->getAllItems() as $orderItem) { $item = array(); $item['sku'] = $orderItem->getSku(); $item['qty'] = $orderItem->getQtyOrdered(); $data['items'][] = $item; } // TODO: Do something with your data array } } A: You can export it to a .txt/csv/xml/php file and grab it from there with your database. Something like this: // choose correct path $path = $_SERVER['DOCUMENT_ROOT'] . '/magento/folder/orders/'; if (!is_dir($path)) { mkdir($path); } // create filename $orderId = Mage::getSingleton('checkout/type_onepage') ->getCheckout()->getLastOrderId(); $order = Mage::getModel('sales/order')->load($orderId); $orderNo = $order->getIncrementId(); // format 20090403_141048_order_100000007_7.xml $filename = date('Ymd_His') . '_order_' . $orderNo . '_' . $orderId . '.txt'; // create content $content = 'content here....'; // create TXT Data here // write file to server file_put_contents($path . $filename, $content);
{ "language": "en", "url": "https://stackoverflow.com/questions/7508405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: trouble viewing h2 db used in grails project I'm trying to have a look at the tables generated in h2 db used in Grails project, but something's amiss. I connect to the browser console at http://127.0.1.1:8082/ but all that's there to browse is INFORMATION_SCHEMA and Users. How do I get tho the tables used/generated by the app? Just started building out the app and only few domain classes are in place and I'm trying to get a feel for working h2. Prior to that I've been using PostgreSql in all projects so this is very unnerving for the moment. Thanks in advance A: Are you using the right JDBC URL when logging in? The default in grails is jdbc:h2:mem:devDB. When an non-existing URL is given, like jdbc:h2:blabla, an empty database is created, with the default INFORMATION_SCHEMA and Users as you described. Make sure you connect to the URL where your grails application stores its tables. You can find the URL in $GRAILS_PROJECT/config/DataSource.groovy, after the url definition. environments { development { dataSource { pooled = false logSql = false username = "sa" password = "" dialect = "com.hp.opr.hibernate.dialect.H2Dialect" driverClassName = "org.h2.Driver" dbCreate = "create-drop" url = "jdbc:h2:mem:devDB;DB_CLOSE_DELAY=-1;MVCC=TRUE" } } } A: If you're using 2.0 the web console is enabled by default in dev mode and can be enabled in other environments: http://grails.org/doc/2.0.0.M2/guide/conf.html#databaseConsole If you're not using 2.0 yet you can install the http://grails.org/plugin/dbconsole plugin or follow the link to my blog post and set it up yourself if you want to customize the url (or if you're using Grails pre-1.3.6 since the plugin has an artificial version restriction to 1.3.6+) A: ... so in datasource I changed the url to: url = "jdbc:h2:rswDb" (removing the 'mem' part and changing the name of the db). Then 3 db files showed up in the root dir of the project. Next, in db console set the jdbc url to: jdbc url: jdbc:h2:~/work/web/rsw/rswDb ... and when I hit 'connect' all the tables were there! Thanks again!
{ "language": "en", "url": "https://stackoverflow.com/questions/7508409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: mysql join question - am i doing this right Hi I have a coupon system that uses one table (called "coupons") to store info about each type of available coupon that one could generate, and another table (generatedcoupons) to store info about each coupon generated. I'm having a hard time comparing info in each table. The schemas: table: coupons +----+------+--------------------+---------------+ | id| owner| date_expiration| limit_per_user| | 15| 34| 2011-09-18 00:00:00| 2| +----+------+--------------------+---------------+ table: generatedcoupons +----+----------+------+--------------------+------+--------+ | id| coupon_id| owner| date| used| user_id| | 1| 15| 34| 2011-09-17 00:00:00| false| 233| +----+----------+------+--------------------+------+--------+ I'm trying to select all expired coupons for a given user. Is this correct? select * from coupons join generatedcoupons on user_id = 233 and coupon_id=coupons.id where coupons.owner=34 and (curdate()>date(coupons.date_expiration) A: You need to join on the owner and the coupon id. Then put the values that you want to filter by in the where clause. select * from coupons c join generatedcoupons g on c.owner=g.owner and g.coupon_id=c.id where g.user_id = 233 and c.owner=34 and (curdate()>date(c.expiration_date) A: A few things: * *Your SQL has an error since the name of the column is expiration_date not date_expiration. *If the owner of coupon_id 15 is always (by definition) owner 34 then you should not repeat the owner column in the generatedcoupons table. To do so is redundant and potentially creates a situation in which the two tables disagree in such a way that you have no way to figure out what the correct data is. *You correctly understand about the JOIN part of the query and the WHERE part of the query, but you misplace a filter condition (user_id = 123) in the JOIN part instead of the WHERE part. *You tagged your question nested-queries, but the question doesn't actually involve any nested queries, but rather a straightforward JOIN.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Backbone.Model.extend() is not a function", what have I done wrong? I am having a crack at Backbone and decided to open a jsFiddle to play around. Unfortunately, I keep getting this error being thrown: Backbone.Model.extend is not a function My code: var Model = Backbone.Model.extend(); I got this piece of code from a Backbone tutorial. The fiddle. What have I done wrong? A: You need to include underscore.js before backbone.js as in this updated version of your fiddle: http://jsfiddle.net/ambiguous/AFmQ2/1/ From the fine manual: Backbone's only hard dependency is Underscore.js.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Trouble with Recursion in Python Working with python 2.7. The following code allows me to input the winning percentage of two teams (WP_1 and WP_2) a number of wins (k) and determine given the two team's winning percentages, the probability that team one will have more wins at the end of the season (Playoff_Probability): def PlayoffProb(WP_1, k, WP_2): TProb_2 = 0 p = float(WP_1)/1000 q = float(WP_2)/1000 n = 162.0 G = math.factorial(n)/(math.factorial(k)*math.factorial(n-k)) Prob = G*(p**k)*((1-p)**(n-k)) for c in range(0, k): G_2 = math.factorial(n)/(math.factorial(c)*math.factorial(n-c)) Prob_2 = G_2*(q**c)*(1-q)**(n-c) TProb_2 += Prob_2 Playoff_Probability = Prob*TProb_2 print Playoff_Probability print TProb_2 But what would be a lot easier is if the function could be written recursively so that it would perform the same operation over every possible value of k and return the total probability of ending the season with more wins (which I believe should be given by the Playoff_Probability for each value run through the function of k, which I've tried to set equal to Total_Playoff_Probability). I've tried the following code, but I get a TypeError telling me that 'float' object is not callable at the return Total_Playoff_Probability step. I'm also not at all sure that I've set up the recursion appropriately. def PlayoffProb2(WP_1, k, WP_2): TProb_2 = 0 Total_Playoff_Probability = 0 p = float(WP_1)/1000 q = float(WP_2)/1000 n = 162.0 G = math.factorial(n)/(math.factorial(k)*math.factorial(n-k)) Prob = G*(p**k)*((1-p)**(n-k)) for c in range(0, k): G_2 = math.factorial(n)/(math.factorial(c)*math.factorial(n-c)) Prob_2 = G_2*(q**c)*(1-q)**(n-c) TProb_2 += Prob_2 Playoff_Probability = Prob*TProb_2 Total_Playoff_Probability += Playoff_Probability if k == 162: return Total_Playoff_Probability else: return PlayoffProb2(WP_1, k+1, WP_2) Any help would be greatly appreciated! A: return Total_Playoff_Probability(WP_1, k+1, WP_2) I think you meant return PlayoffProb2(WP_1, k+1, WP_2) You've got that error because you are trying to treat a floating point number as a function. Obviously, that doesn't compute. EDIT Actually, it should be: return Total_Playoff_Probability + PlayoffProb2(WP_1, k+1, WP_2) As it is, you aren't doing anything with Total_Playoff_Probability after you calculate it. If k != 167, you just return the value for k+1. A: You've called your function PlayoffProb2. You must use that name when you recurse.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jquery form validation I am using this script to see if a user has left any inputs invalid clientside. $('#login_submit').click(function() { var login_email = $('#login_email').val(); var login_password = $('login_password').val(); if (login_email.length == 0) { $('#login_email').css('background', 'red'); } if (login_password.length == 0) { $('#login_password').css('background', 'red'); } }); One thing I cannot work out is how to stop the form submitting as it would. I have tried return false; but this then makes the input fields backgrounds just flicker red. Regards, A: do <input type="submit" onsubmit="return submitValidate()" /> and change your JS to: function submitValidate() { var login_email = $('#login_email').val(); var login_password = $('login_password').val(); var submit = true; if (login_email.length == 0) { submit = false; $('#login_email').css('background', 'red'); } if (login_password.length == 0) { submit = false; $('#login_password').css('background', 'red'); } return submit; } A: $('#your-form-id').submit(function() { var errors = 0; var login_email = $('#login_email').val(); var login_password = $('login_password').val(); if (login_email.length == 0) { $('#login_email').css('background', 'red'); errors++; } if (login_password.length == 0) { $('#login_password').css('background', 'red'); errors++; } return errors ? false : true; }); Fiddle demo: http://jsfiddle.net/xjNut/ Just make sure you don't have an input with name="submit" in the form. All other attributes are fine to have in the input. A: Your problem is most likely because you're using a submit button: <input type="submit" ... /> You need to change it to a regular button: <input type="button" ... /> Then in your function you'll need to submit the form when the code is valid: $('#formId').submit();
{ "language": "en", "url": "https://stackoverflow.com/questions/7508430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Print repeated numbers only one time in c# I have an array with "n" numbers and I need to print all repeated numbers only one time i made this code, but something is wrong for (int i = 0; i < numbers.Length; i++) { for (int j = 1; j < numbers.Length; j++) { if (numbers[i] == numbers[j] && i!=j) { Console.WriteLine(numbers[i]); break; } } } then if my array have the elements {2,3,1,5,2,3} the program prints : 2 3 3 what can I do? A: You can use: using System.Linq; … foreach(var number in numbers.Distinct()) Console.WriteLine(number); edit I may have misunderstood the requirement. If you only want to output the numbers that appear more than once, then you can use: foreach(var group in numbers.GroupBy(n => n).Where(g => g.Count() > 1)) Console.WriteLine(group.Key); A: var query = numbers.GroupBy(x => x) .Where(g => g.Skip(1).Any()) .Select(g => g.Key); foreach (int n in query) { Console.WriteLine(n); } Or, alternatively... var dict = new Dictionary<int, int>(); foreach (int n in numbers) { int count; dict.TryGetValue(n, out count); if (count == 1) { Console.WriteLine(n); } dict[n] = count + 1; } A: The problem in your code: you get 3 repeated because when i is 1 (looking at the first 3) there's another 3 in the list at the end, and when i is 5 (looking at the last 3) there's another three in the list near the beginning. Instead you should look at only those numbers which come after your current position - change to int j = i; so that you only look at the positions after your current position, and you won't get repeated results. for (int i = 0; i < numbers.Length; i++) { for (int j = i; j < numbers.Length; j++) { if (numbers[i] == numbers[j] && i!=j) { Console.WriteLine(numbers[i]); break; } } } Having said that, your algorithm is not as efficient as using a built in algorithm. Try GroupBy var duplicates = numbers.GroupBy(n => n) .Where(group => group.Count() > 1); foreach (var group in duplicates) { Console.WriteLine("{0} appears {1} times", group.Key, group.Count()); } A: One way to get distinct numbers is var uniqueNumbers = numbers.Distinct().ToArray() and then iterate over uniqueNumbers like you have in your snippet with numbers. A: You can add the number to a HashSet as you loop and then only print if not in hash set. That allows you to do it in one pass. The algorithm above is n^2 which should be avoided. A: // deletes an integer if it appears double #include <iostream.h> #include <conio.h> int main () { int count=0; int ar[10]={1,2,3,3,3,4,5,6,7,7}; for (int i=0; i<10; i++) { if (ar[i]==ar[i+1]) count++; else cout << ar[i]; } getch(); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7508431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Replacing Microsoft.VC90.CRT WinSxS policy file with local config file On Windows XP, I have an .exe which runs with msvcp90.dll, msvcr90.dll, and Microsoft.VC90.CRT.manifest in my local application directory. I also have a policy file for these .dlls in C:\WINDOWS\WinSxS\Policies, which was installed by the Visual C++ 2008 SP1 Redistributable Package. I'd like to delete this policy file and use an app config file in my local directory instead. The policy file is: <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity type="win32-policy" name="policy.9.0.Microsoft.VC90.CRT" version="9.0.30729.1" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"/> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"/> <bindingRedirect oldVersion="9.0.20718.0-9.0.21022.8" newVersion="9.0.30729.1"/> <bindingRedirect oldVersion="9.0.30201.0-9.0.30729.1" newVersion="9.0.30729.1"/> </dependentAssembly> </dependency> </assembly> My config file is: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"/> <bindingRedirect oldVersion="9.0.20718.0-9.0.21022.8" newVersion="9.0.30729.1"/> <bindingRedirect oldVersion="9.0.30201.0-9.0.30729.1" newVersion="9.0.30729.1"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration> Dependency Walker reports side-by-side errors when using the config file instead of the policy file - what's wrong? Also, should the config file be named <application>.exe.config, or Microsoft.VC90.CRT.config? (To clarify, no errors appear when using the policy file. However, the client here is not allowed to install the redistributable package. The MSDN docs state that an app config file can redirect the application to use different versions of the same assembly (per-application configuration), and that it can override an existing policy (publisher configuration) file if needed. So I think it must be possible to use a local app config file, and that something in the file above is missing or incorrect.) A: Your configuration data is under the <runtime> node. It should instead be under the <windows> node. I have to caution that shipping application configuration files that contain binding redirects is highly discouraged and is inteded for system administrators dealing with an appcompat problem on the machines they adminster. Application developers should instead be authoring their applications to work with the latest revision of the specific version of the CRT they depend on and use the default global policy that ships with that version. In fact, starting with Windows 2003, using binding redirects in an application configuration file requires an entry in the application compatibility database. A: It is my understanding that the c runtimes cannot be redirected in this way for security reasons. Your options are to statically build the runtimes into your project or load the DLLs from your application directory with out the Side-By-Side system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JQuery Mobile - blue button on release When releasing a button in JQuery Mobile it will turn blue for just a short duration while the action is called. It can even be seen on JQuery Mobile own website. My question is, how do i get rid of the button getting blue? Thanks :) A: Set the -webkit-tap-highlight-color attribute in your CSS. A: Maybe a bit late, but an <a> element without the href attribute has no blue border. <a data-role="button">Button</a> Then just use the click event to specify the behaviour (example).
{ "language": "en", "url": "https://stackoverflow.com/questions/7508435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: send session var with php cUrl Am trying to send data between scripts within my application. Problem is session id is not responding. Script 1 is... <?php session_start(); $_SESSION['id'] = 1; $data = "data to be sent to script"; $ch = curl_init("http:.../myscript.php"); $nvp = "&data=$data"; curl_setopt($ch, CURLOPT_POSTFIELDS, $nvp); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); echo curl_exec($ch); ?> myScript.php is... <?php session_start(); $id = $_SESSION['id']; $data = $_POST['data']; $result = function idData($id, $data); // returns matching results. echo "Session Id = $id <br />"; echo "Id result = $result <br />"; ?> However myScript.php is not able to access the session data as per normal. Is there a work around for this? What could the possible cause be? Thanks A: I believe you're looking for CURLOPT_COOKIE curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id()); A: In script 1 you could use CURLOPT_COOKIE if you keep track of the session ID from the response yourself. I don't think you need or want session_start in script 1 if it is going to be making multiple requests to myscript.php that creates a session. Use this in script 1: curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt'); // set cookie file to given file curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt'); // set same file as cookie jar And then make your request as normal. Any cookies set by myscript.php will be saved to the cookie jar file when the request completes, the cookiefile will be checked for any cookies to be sent prior to sending the request. You could manually track the php session cookie from the curl request and use CURLOPT_COOKIE as well. A: You miss one option parameter for using post. Please add this one, it should work: curl_setopt($ch, CURLOPT_POST, true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7508438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Convert C++ to C# I have 2 functions in C++ which need to be converted to C#. Below are the details of the functions C++ void MyClass::GetArg(string argument, int minError, string* arg1, string* arg2, string* arg3, string* arg4, string* arg5) { if(arg1 != null) *arg1 = GetArg(argument, 1, minError) if(arg2 != null) *arg2 = GetArg(argument, 2, minError) if(arg3 != null) *arg3 = GetArg(argument, 3, minError) if(arg4 != null) *arg4 = GetArg(argument, 4, minError) if(arg5 != null) *arg5 = GetArg(argument, 5, minError) } string MyClass::GetArg(string argument, int argNum, int minError) { //Whatever logic } And I am seeing function call as GetArg(argString, 3, &v1, &v2, &v3); The question I have here is, I am not seeing any overloaded function which takes 5 arguments. Are those additional arguments, arg4 and arg5 optional? I have created a similar function in C# as below public string GetArg(string argument, int argNum, int minError) { //Logic goes here } I have converted GetArg(argString, 3, &v1, &v2, &v3) into 3 separate function calls as below string v1 = GetArg(argString, 1, 3); string v2 = GetArg(argString, 2, 3); string v3 = GetArg(argString, 3, 3); I am not sure what is the impact of converting as above as I have very minimum knowledge in C++. I would appreciate if anyone could show me a better way of converting this. A: Your C++ code won't compile. All argument sare required in C++, unless you specifically make them optional (by using an = default) or by using the variable arguments mechanism leftover from C As such, it's impossible to make C# do the same thing, since the code you posted is illegal in C++. A: You need to pass parameters by reference and use .NET framework 4 using System.Runtime.InteropServices; public class MyClass { public string GetArg(string argument, int minError, ref string arg1, ref string arg2, ref string arg3, [Optional] ref string arg4, [Optional] ref string arg5) { if(arg1 != null) arg1 = GetArg(argument, 1, minError); if(arg1 != null) arg2 = GetArg(argument, 2, minError); if(arg1 != null) arg3 = GetArg(argument, 3, minError); if(arg1 != null) arg4 = GetArg(argument, 4, minError); if(arg1 != null) arg5 = GetArg(argument, 5, minError); } } call GetArg(argString, 3, v1, v2, v3);
{ "language": "en", "url": "https://stackoverflow.com/questions/7508441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the best way to sort a hashtable by value? Now i have to copy the hastable to a list before sorting it: (defun good-red () (let ((tab (make-hash-table)) (res '())) (dotimes (i 33) (setf (gethash (+ i 1) tab) 0)) (with-open-file (stream "test.txt") (loop for line = (read-line stream nil) until (null line) do (setq nums (butlast (str2lst (substring line 6)))) (dolist (n nums) (incf (gethash n tab))) )) **(maphash #'(lambda (k v) (push (cons k v) res)) tab)** (setq sort-res (sort res #'< :key #'cdr)) (reverse (nthcdr (- 33 18) (mapcar #'car sort-res))) )) BTW, what's the better way to fetch the first N elements of a list ? A: A hash-table is inherently unordered. If you want it sorted, you need to initialize some sort of ordered data structure with the contents. If you want to fetch the first N elements of a sequence, there's always SUBSEQ. A: Vatine's answer is technically correct, but probably not super helpful for the immediate problem of someone asking this question. The common case of using a hash table to hold a collection of counters, then selecting the top N items by score can be done like this: ;; convert the hash table into an association list (defun hash-table-alist (table) "Returns an association list containing the keys and values of hash table TABLE." (let ((alist nil)) (maphash (lambda (k v) (push (cons k v) alist)) table) alist)) (defun hash-table-top-n-values (table n) "Returns the top N entries from hash table TABLE. Values are expected to be numeric." (subseq (sort (hash-table-alist table) #'> :key #'cdr) 0 n)) The first function returns the contents of a hash table as a series of cons'd pairs in a list, which is called an association list (the typical list representation for key/value pairs). Most Lisp enthusiasts already have a variation of this function on hand because it's such a common operation. This version is from the Alexandria library, which is very widely used in the CL community. The second function uses SUBSEQ to grab the first N items from the list returned by sorting the alist returned by the first function using the CDR of each pair as the key. Changing :key to #'car would sort by hash keys, changing #'> to #'< would invert the sort order.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Generic T with Enum and casting T to Enum I searched around and couldn't find any examples doing this, though this was helpful: Create Generic method constraining T to an Enum I have a generic function which wraps a function in an API (which I can't touch). The wrapped function takes a System.Enum and returns the same. My generic version simplifies the things quite a bit in the non-stripped down version of this example. The problem is, I couldn't case from T to System.Enum, or back again, since T isn't constrained to System.Enum (at least that is my understanding). The following code works but I am curious to know if there are any hidden traps, or better ways, since I am very new to generics: using System using System.Collections.Generic ... public T EnumWrapper<T>(T enumVar) where T : struct, IFormattable, IConvertible, IComparable { if (!typeof(T).IsEnum) throw new ArgumentException("Generic Type must be a System.Enum") // Use string parsing to get to an Enum and back out again Enum e = (Enum)Enum.Parse(typeof(T), enumVar.ToString()); e = WrappedFunction(e); return (T)Enum.Parse(typeof(T), e.ToString()); } If this is ok, then let this serve as an example. I couldn't find this and at the very least it is a working work-around. P.S. Performance isn't an issue in this case. thought I was thinking string-work might be slow and I am always interested in performance tips. A: You can make the constraint tighter. All enums implement the followable interfaces IFormattable,IConvertible and IComparable. This will pretty much limit you to primitives and enums and classes which act like them. Alternatively, if you really want to create a method or class only bindable to enums you can do the following: public abstract class InvokerHelper<T> where T : class { public abstract R Invoke<R>(R value) where R : struct,T; } public class EnumInvoker : InvokerHelper<Enum> { public override R Invoke<R>(R value) { return (R)WrappedMethod(value); } } Its clunky and can't be used for extension methods, but you could make this a singleton object and then only have generic methods. Alternatively, you can write your code in C++/CLI or Reflection.Emit which allows you to create classes that can have the constraint where T:struct,Enum Actually it appears you just want to take a generic T call a method that takes an enum and return it as T right? Then the following will work. public static T WrappedMethodInvoker<T>(T value) where T:struct,IComparable,IFormattable,IConvertible { Enum e; if((e = value as Enum) == null) throw new ArgumentException("value must be an Enum") object res = WrappedMethod(e); return (T)res; } This is a little easier. First we know T is an Enum, you can use the as operator to try casting to a nullable type (reference type or nullable struct), which Enum most certainly is. From there we can use covariance of return types, WrappedMethod returns an Enum, which means we can store it in an object. Finally, when you have an object in a generic method you are syntactically allowed to cast it to T. It might fail, but we know for a fact the method returns an Enum of the same type. There are some costs to know in that you are always boxing and unboxing. Is the wrapped method generic? I've edited the answer to show the first technique revised to your example case. Its extremely simple and type safe, but you always have to have an EnumInvoker to perform the actions. Both answers should perform about the same unfortunately, as calling the WrappedMethod will box value if its argument is Enum. The only advantage of the first method is that it is strongly typed, but generic virtual methods are the slowest methods to invoke as far as I'm aware. So avoiding the type check might not be worth he cost of easier invocation. A: The matter is simple here: C#'s Type System doesn't let you specify a constraint on an Enum type. The code has no obvious pitfalls, besides it won't trigger a compile time error if you pass it an IConvertible struct that is not an Enum. In this case it will fail at runtime, which is not desirable but there is no better option, really. You might be able to enforce this with CodeContracts at compile time though, although I don't know enough about CodeContracts (though I fell in love with them) yet, to give you a definite answer here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PHP Large Float, need to round I have a program that is giving me this number: 9.1466606511048E-8 I need to round that, using most obvious functions in PHP gives me 0. A: That's because that number has a value of 0.000000091466606511048, which is very close to zero. Perhaps you need to be more specific about what sort of rounding you want. A: How many decimals are you attempting to round to? The number that you specified is the same as: 0.000000091466606511048 If you're using the round function without specifying to what decimal place you want to round, then it is going to round to zero because of the value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: System.Threading.Tasks.Parallel error in IronRuby In C# class ParallelTest { public static void Main() { System.Threading.Tasks.Parallel.ForEach(new []{1,2,3,4,5,6,7,8}, x => { System.Console.WriteLine(x); } ); } } Result 4 5 6 7 8 2 1 3 But, in IronRuby(1.1.3). Some line empty or lose linefeed. System::Threading::Tasks::Parallel::ForEach([1,2,3,4,5,6,7,8], Proc.new {|x| puts x; }) Result 1734 2 5 6 8 What coused this problem? Is this just a bug? A: It seems IronRuby's puts is not thread-safe. If you use Console.WriteLine() in IR, it works fine: System::Threading::Tasks::Parallel::ForEach([1,2,3,4,5,6,7,8], Proc.new {|x| System::Console::WriteLine(x) })
{ "language": "en", "url": "https://stackoverflow.com/questions/7508460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .NET Centralized Configuration for Windows Services and WCF Web Services Does anybody know of a way to centralize a .NET app config so that it can be used by multiple windows services and multiple wcf web services on a computer? They are all installed in separate folders under \program files. Our software currently has a separate app config for each application but it's getting crazy trying to maintain it all. We have though of having each application reference a gac dll that can read from a central file but that will probably not work due to the wcf client configuration for those apps that call wcf web services. For example we will typically have 2 or more wcf webservices and/or 2 or more windows services on a computer and they each have their own configuration files. tia A: .NET configuration file can reference another config file. If your apps are deployed similar to this: Program Files \ MyCompany \ Shared.config Program Files \ MyCompany \ ClientA \ ClientA.config You can reference Shared.config from ClientA.config: <?xml version="1.0" encoding="utf-8"?> <configuration> ... <appSettings file="..\Shared.config"> You can also try putting settings into machine.config. From Configuring Services Using Configuration Files: ... This mechanism allows machine-wide settings to be defined in the Machine.config file. The App.config file can be used to override the settings of the Machine.config file; you can also lock in the settings in Machine.config file so that they get used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert from byte array to string and string to byte array in java Possible Duplicate: Conversion of byte[] into a String and then back to a byte[] I have the following piece of code, I'm trying to get the test to pass, but can't seem to get my head around the various forms of encoding that go on in the java world. import java.util.Arrays; class Test { static final byte[] A = { (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77, (byte)0x88, (byte)0x99, (byte)0x00, (byte)0xAA }; public static void main(String[] args) { String s = new String(A); byte[] b = s.getBytes(); if (Arrays.equals(A,b)) { System.out.println("TEST PASSED!"); } else { System.out.println("TEST FAILED!"); } } } I guess my question is: What is the correct way to convert a byte array of arbitary bytes to a Java String, then later on convert that same Java String to another byte array, which will have the same length and same contents as the original byte array? A: Try a specific encoding: String s = new String(A, "ISO-8859-1"); byte[] b = s.getBytes("ISO-8859-1"); ideone link A: Use Base64. Apache Commons Codec has a Base64 class which supports the following interface: String str = Base64.encodeBase64String(bytes); byte[] newBytes = Base64.decodeBase64(str);
{ "language": "en", "url": "https://stackoverflow.com/questions/7508464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OpenGL on Mac OS X for an iPhone developer I'm looking for a good example of a basic OpenGL App for Mac OS X, but not too simple. I have a good solid base of experience with iOS and objective-c, but I've never built a Mac OS X App. All I've been able to find are super simple examples that do all the drawing and logic in drawRect: or overly complex examples with layers and layers of abstraction. I don't want to use Glut, SDL, or any other 3rd party libs or engines. I want to be able to drive a Game Loop and use CADisplayLink like I do on my iOS games. I'd also rather not use .xib files because I like to understand what's going on and having that black box there hides too much for me, although I'd be happy to use it as a first step if it got me everything else (game loop, CADisplayLink, etc). My iOS code creates it's OpenGL Views by hand, but there seems to be enough of a difference between iOS and OS X that I'm having trouble making heads or tails of it. I just need to get a Window and an OpenGL view and be able to draw to that via the game loop. Can someone point me to a good resource? The Apples examples jump between to simple and too complex as does everything else I can find on the Internet. A: Sorry I can't answer to your questions. I always did use XIB files (a looong time ago, I too always wanted to re-invent the wheel, but now I'm lazy and prefer getting stuff done :p) and I never used display links. What don't you like about overriding drawRect: ? And the sample I used to get started with OpenGL was this one : http://developer.apple.com/library/mac/#samplecode/CocoaGL/Introduction/Intro.html#//apple_ref/doc/uid/DTS10004501 Not too complicated, and simple enough to understand it (and it doesn't use any XIB, if I remember well :p)
{ "language": "en", "url": "https://stackoverflow.com/questions/7508465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: asyn vs sync forEach,map,filter Looking at Async and a async branch of underscore.js it appears asyn versions of the Sync forEach,map, and filter are present. Considering Javascript is single threaded what value is there in returning a sorted,mapped,forEached... array vs passing the returned value to a callback function? A: Asynchronous iteration functions like this are useful when what you do with each item depends on an underlying asynchronous task. For instance, in Node.js, filesystem operations are asynchronous (they happen in a separate, non-JavaScript thread and call a callback when they’re done). If you want to, say, map a list of filenames to information on those files, you won’t be able to return a result to map until the filesystem operation calls back. Similarly, JavaScript database drivers tend to be asynchronous (they do their work in another thread, and call back a JavaScript function when they’re done). For example, let’s say you have a list of user IDs (like a list of users involved in a Stack Overflow question), and you’d like to map them to detailed information about each user. With async.js, that might look like this: async.map([2389, 6344, 27], function(id, callback){ database.users.find({ id: id }, function(error, user){ if (error) { callback(error); } else { callback(null, { name: user.name, reputation: user.reputation, picture: user.picture }); } }) }, function(error, results){ /* results contains: [ { name: "Bob", reputation: 10, picture: "http://…" }, { name: "Fred", reputation: 2910, picture: "http://…" }, { name: "Steve", reputation: 25000, picture: "http://…" } ] */ } ); The iterator function will be called for each item in the array, and will start a database query to get details about that user. It won’t wait for each query to finish before starting the next one. The database queries might finish very quickly, or they might take a little while. If they were synchronous, they could only be run one at a time. Worse, the JavaScript thread wouldn’t be able to do anything else while the database queries were running. This way, it doesn’t matter how long the database queries take. While they go, the JavaScript thread might be idle, or it might be off dealing with something else (like another request to the server). When each database request finishes (and they may not even finish in the same order they were started!), it calls its callback function, which puts the information about the user into an object and hands it to its callback. async.js keeps track of which iterations have returned so far, and calls the final callback only once every one of them has finished. You can find similar examples in the async.js documentation. In the browser there are fewer asynchronous operations, but you might use async.js with requests to the server, to load a set of resources (like scripts or images) and make sure they all loaded successfully, or send messages between windows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Regular Expression conditionals, e.g. "and" / "or" Is there a way using regular expressions to find grep 'a &| b &| c' #pseudo code If 'a' is found also check for 'b' and if 'a' is not found also check for 'b'? etc... A: You can just nest the needed values in parenthesis for and support. Yes there is or | support. (ab)|(a(c|b)) I would have left it in a comment but don't have enough rep. A: Is this what you mean? (a)?(b)?(c)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7508468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GetGlyphOutline() and UTF-16 surrogate pairs I'm using the GDI GetGlyphOutlineW function to get the outline of unicode characters, and it works fine except that it does not work with surrogate pairs (U+10000 and higher). I've tried converting the surrogate pair into a UTF-32 character, but this does not appear to work. How can I get glyph outlines of Supplementary Multilingual Plane characters? A: Some Suggestions: * *Does the particular Unicode code point you are trying to get actually exist in the font that is selected in the DC passed to the GetGlyphOutlineW function? *Follow the directions on this page to enable surrogate pairs in Windows. *Use the Uniscribe functions for character manipulation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is C++ preprocessor metaprogramming Turing-complete? I know C++ template metaprogramming is Turing-complete. Does the same thing hold for preprocessor metaprogramming? A: Well macros don't directly expand recursively, but there are ways we can work around this. The easiest way of doing recursion in the preprocessor is to use a deferred expression. A deferred expression is an expression that requires more scans to fully expand: #define EMPTY() #define DEFER(id) id EMPTY() #define OBSTRUCT(...) __VA_ARGS__ DEFER(EMPTY)() #define EXPAND(...) __VA_ARGS__ #define A() 123 A() // Expands to 123 DEFER(A)() // Expands to A () because it requires one more scan to fully expand EXPAND(DEFER(A)()) // Expands to 123, because the EXPAND macro forces another scan Why is this important? Well when a macro is scanned and expanding, it creates a disabling context. This disabling context will cause a token, that refers to the currently expanding macro, to be painted blue. Thus, once its painted blue, the macro will no longer expand. This is why macros don't expand recursively. However, a disabling context only exists during one scan, so by deferring an expansion we can prevent our macros from becoming painted blue. We will just need to apply more scans to the expression. We can do that using this EVAL macro: #define EVAL(...) EVAL1(EVAL1(EVAL1(__VA_ARGS__))) #define EVAL1(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__))) #define EVAL2(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__))) #define EVAL3(...) EVAL4(EVAL4(EVAL4(__VA_ARGS__))) #define EVAL4(...) EVAL5(EVAL5(EVAL5(__VA_ARGS__))) #define EVAL5(...) __VA_ARGS__ Now if we want to implement a REPEAT macro using recursion, first we need some increment and decrement operators to handle state: #define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__) #define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__ #define INC(x) PRIMITIVE_CAT(INC_, x) #define INC_0 1 #define INC_1 2 #define INC_2 3 #define INC_3 4 #define INC_4 5 #define INC_5 6 #define INC_6 7 #define INC_7 8 #define INC_8 9 #define INC_9 9 #define DEC(x) PRIMITIVE_CAT(DEC_, x) #define DEC_0 0 #define DEC_1 0 #define DEC_2 1 #define DEC_3 2 #define DEC_4 3 #define DEC_5 4 #define DEC_6 5 #define DEC_7 6 #define DEC_8 7 #define DEC_9 8 Next we need a few more macros to do logic: #define CHECK_N(x, n, ...) n #define CHECK(...) CHECK_N(__VA_ARGS__, 0,) #define NOT(x) CHECK(PRIMITIVE_CAT(NOT_, x)) #define NOT_0 ~, 1, #define COMPL(b) PRIMITIVE_CAT(COMPL_, b) #define COMPL_0 1 #define COMPL_1 0 #define BOOL(x) COMPL(NOT(x)) #define IIF(c) PRIMITIVE_CAT(IIF_, c) #define IIF_0(t, ...) __VA_ARGS__ #define IIF_1(t, ...) t #define IF(c) IIF(BOOL(c)) #define EAT(...) #define EXPAND(...) __VA_ARGS__ #define WHEN(c) IF(c)(EXPAND, EAT) Now with all these macros we can write a recursive REPEAT macro. We use a REPEAT_INDIRECT macro to refer back to itself recursively. This prevents the macro from being painted blue, since it will expand on a different scan(and using a different disabling context). We use OBSTRUCT here, which will defer the expansion twice. This is necessary because the conditional WHEN applies one scan already. #define REPEAT(count, macro, ...) \ WHEN(count) \ ( \ OBSTRUCT(REPEAT_INDIRECT) () \ ( \ DEC(count), macro, __VA_ARGS__ \ ) \ OBSTRUCT(macro) \ ( \ DEC(count), __VA_ARGS__ \ ) \ ) #define REPEAT_INDIRECT() REPEAT //An example of using this macro #define M(i, _) i EVAL(REPEAT(8, M, ~)) // 0 1 2 3 4 5 6 7 Now this example is limited to 10 repeats, because of limitations of the counter. Just like a repeat counter in a computer would be limited by the finite memory. Multiple repeat counters could be combined together to workaround this limitation, just like in a computer. Furthermore, we could define a FOREVER macro: #define FOREVER() \ ? \ DEFER(FOREVER_INDIRECT) () () #define FOREVER_INDIRECT() FOREVER // Outputs question marks forever EVAL(FOREVER()) This will try to output ? forever, but will eventually stop because there are no more scans being applied. Now the question is, if we gave it an infinite number of scans would this algorithm complete? This is known as the halting problem, and Turing completeness is necessary to prove the undecidability of the halting problem. So as you can see, the preprocessor can act as a Turing complete language, but instead of being limited to the finite memory of a computer it is instead limited by the finite number of scans applied. A: No. The C++ preprocessor does not allow for unlimited state. You only have a finite number of on/off states, plus a include stack. This makes it a push-down automaton, not a turing machine (this ignores also the fact that preprocessor recursion is limited - but so is template recursion). However, if you bend your definitions a bit, this is possible by invoking the preprocessor multiple times - by allowing the preprocessor to generate a program which re-invokes the preprocessor, and looping externally, it is indeed possible to make a turing machine with the preprocessor. The linked example uses C, but it should be adaptable into C++ easily enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: If Java is pass-by-value only, can I mandate a final modifier in formal parameters? If Java is strictly pass-by-value for non primitive, isn't it better to establish coding standards like make all formal parameters of methods and constructors final? - to avoid confusion? A: If Java is strictly pass-by-value for non primitive Java is strictly pass-by-value for ALL arguments and ALL results, irrespective of type. And if you don't understand, or don't believe me, read Java is Pass-by-Value, Dammit! ... can I mandate a final modifier in formal parameters? Yes you could, but it would be a bad idea to do it for the reasons that you have given. Declaring a method or constructor's formal parameters to be final means something different to the meaning that you are trying to place on it. Specifically, it means that the parameter can't be assigned to in the body of the method / constructor. Doing this has the following consequences: * *It will actually change the meaning of the code in a way that could cause compilation errors in some cases. (These are good compilation errors ... because they force the programmer to stop doing something that generally makes his code less clear. But fixing takes effort and requires retesting, etc.) *Seasoned Java programmers are not going to read into this the meaning that you intend. (Not that they should need to be reminded ...). *Novice Java programmers are likely to be more confused ... especially if they pick up the incorrect notion that declaring something to be final alters the argument passing semantics! So this does not achieve your aim. The real solution is to educate people that Java ALWAYS uses pass-by-value. (And that includes beating up people who persist in spreading false information and doubt about this ... like your question does!) (In nearly all cases, it is good practice to not update formal parameters, and declaring them final prevents you doing this by accident. So this is good practice. But the reason it is good practice is not what you stated ... and if you did put this into a coding standard with the reasoning that you gave, you would deserve to be roundly criticised.) And if you don't understand, or don't believe me, read Java is Pass-by-Value, Dammit! A: Shahzeb commented that Java does not pass by value for non-primitives; it is pass-by-value for non-primitives in the sense that it passes the value of a reference to the non-primitive. It does not, however, copy objects when you pass them to functions. The final modifier in formal parameter lists shouldn't affect callers one way or the other because methods receive copies of references and copies of primitives; they cannot affect reference and primitive values in caller code. The final modifier does not prevent mutable objects from being altered through the final reference. final can only be of any help to the code in the method it is in. (Someone correct me if I'm wrong, but I believe this is right.) A: One of the use of final in parameters is to avoid your parameter value to be changed by mistake when you write a method. Consider this private method1(final String name){ ... ... String oldname = this.name; name = name; } You forget to add this.name in name.The compiler will give error. This help you /developer to trade a logic error into a compiler error, if you make sure the input parameter cannot be modified. Thus reduce your error prone and debug time :) Hope it helps A: Just to cover other bases, because I think this is what you are thinking about: In C++, it is possible to declare a parameter as "const", which basically means that the data contained in this object will not change as a result of calling this function (I think). http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/PARAMS.html#constRef Java does not have such a modifier. (In Java 7 maybe? Anyone know?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7508476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select columns by name rather than letter in Google Query Language (GQL) with Google Spreadsheets? newbie question, is it possible to select columns by name rather than letter when using Google Query Language with Google Spreadsheets? This works fine for me: "SELECT A, COUNT(B) GROUP BY A" It'd be great if I could use the column headers in the first row, more like a database, as in: "SELECT student, COUNT(detention) GROUP BY student" I suspect it's not possible, but hope this yet another case where my Internet search skills failed me. A: This is currently not possible. The GQL documentation states[1] "Columns are referenced by the identifiers (not by labels). For example, in a Google Spreadsheet, column identifiers are the one or two character column letter (A, B, C, ...)." If you want to do this in a spreadsheet it is possible with the following formula to convert a column header name into a letter (some tweaking might be required +1 (might be +2)). It also relies on column headers being unique and not containing commas =REGEXEXTRACT(ADDRESS(1,COUNTA(SPLIT(LEFT(JOIN(",",TRANSPOSE(1:1)),FIND("your_column_name",JOIN(",",TRANSPOSE(1:1)))),","))+1,4);"[a-zA-Z]+") [1] https://developers.google.com/chart/interactive/docs/querylanguage#Select A: A little simpler: SELECT "&SUBSTITUTE(ADDRESS(1,MATCH("student",Sheet1!A1:B1,0),4),1,"")&", COUNT("&SUBSTITUTE(ADDRESS(1,MATCH("detention",Sheet1!A1:B1,0),4),1,"")&") GROUP BY "&SUBSTITUTE(ADDRESS(1,MATCH("student",Sheet1!A1:B1,0),4),1,"") * *Example in Google Sheets *Detailed explanation A: I found that when you use IMPORTRANGE function on external ranges it converts from a letter to a column number, and will help you in this matter. I've wanted to select a column based on its field name, but the problem for me was that the column to look at was likely to change in the future. So what I did was use the MATCH function to identify the column, so it looks something like =QUERY(IMPORTRANGE("spreadsheet url","NamedRange"),"SELECT Col"&MATCH("FieldName",FieldNameRowAddress/RangeName,FALSE)") The funny thing is you have to allow permission to access itself. I've named my ranges that I'm importing to make it even more future proof. A: if you really want you can fake it: =LAMBDA(student, detention, QUERY({A1:B5}, "SELECT "&student&", COUNT("&detention&") GROUP BY "&student, 1)) ("Col"&MATCH("student", A1:B1, ), "Col"&MATCH("detention", A1:B1, ))
{ "language": "en", "url": "https://stackoverflow.com/questions/7508477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Grouping list element in C# I have the following list: List<string> data = new List<string>(); Then I populate it by fetching the result of a MySQL request: data.Add(name); The list is well populated but I would like to make a grouping, and would like to get the number of each name present in the list: name A = X; name B = X; etc... I tried to do it using data.GroupBy(data, data.Count) but did not work. Any suggestions? A: Try this: from d in data group d by d.Name into gds select new { Name = gds.Key, Count = gds.Count(), } A: Try this: string[] foo = new string[]{"foo","foo","bar","foo","baz","foo"}; var grouping = foo.ToList().GroupBy(x=>x); foreach (var s in grouping.OrderByDescending(x=>x.Count())) { Console.WriteLine(s.Key + " - " + s.Count().ToString()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7508479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Posting images via CURL to a form I've had a tough time trying to find a solution for the following problem, I need to use curl to submit a form on a website, however it also needs to upload a picture its a normal input file field <input type="file" name="image"/> I have a class and the curl function is defined like this function fetch($url, $username='', $data='', $proxy=''){ $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); if(isset($proxy)) { curl_setopt($ch,CURLOPT_TIMEOUT,30); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_PROXYPORT, $proxy); curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'proxyadmin:parola'); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FRESH_CONNECT,true); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/3.0 (compatible; MSIE 6.0; Windows NT 5.0)"); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 5); if($username) { curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie/{$username}.txt"); curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie/{$username}.txt"); } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); if (is_array($data) && count($data)>0){ curl_setopt($ch, CURLOPT_POST, true); $params = http_build_query($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } if (is_array($this->headers) && count($this->headers)>0){ curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); } $this->result = curl_exec($ch); $curl_info = curl_getinfo($ch); $header_size = $curl_info["header_size"]; $this->headers = substr($this->result, 0, $header_size); $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $this->error = curl_error($ch); curl_close($ch); } Anyone could help me? very lost A: If you change the following block of code: // from if (is_array($data) && count($data)>0){ curl_setopt($ch, CURLOPT_POST, true); $params = http_build_query($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } // to if (is_array($data) && count($data)>0) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } And to have it post the file uploaded by the user, set up your data array like this: // make sure $_FILES['file'] has been uploaded and is valid $data = array('field' => 'value', 'name' => 'test', 'email' => 'something', 'file' => '@' . $_FILES['file']['tmp_name'] ); fetch($url, $username, $data); That will tell curl to send a form post with a file upload. By setting the post fields to an array and prepending an & to the full path of a file that is a value of the array, curl will send an multipart/form-data post request with your file upload. See curl file upload example
{ "language": "en", "url": "https://stackoverflow.com/questions/7508483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reading CrystalReport's Field Value Programmatically I'm using C#.NET to programmatically load a Crystal Report document (which gets its data from a database) and then export it as a PDF. I'm stuck trying to read a fields (abc123) value from within the report (I want to use it in the filename). I don't mind where this field is in the crystal report; and it will not be repeated, but it needs to be a field in the report. My code so far: // Setup ReportDocument reportTemplate = new ReportDocument(); reportTemplate.Load(textBox1.Text); reportTemplate.Refresh(); reportTemplate.ReadRecords(); // Load the current reports name from the report summary information String ReportName = reportTemplate.SummaryInfo.ReportTitle.ToString(); // Load the current reports "abc123" field from the report // ???? // Export the report as PDF reportTemplate.Export(); I've tried: // Load the current reports "abc123" field from the report String abcField = ((TextObject)rpt.Section2.ReportObjects["abc123"]).Text String abcField = reportTemplate.ReportDefinition.ReportObjects["abc123"].ToString(); String abcField = reportTemplate.Rows.ReportDocument.ReportDefinition.ReportObjects["abc123"]; Without luck. Can anyone give some pointers? I can preview the report using crystalReportView1 object and the field is populated there. A: Unfortunately you will not be able to pull a calculated field value from code behind. The calculated field value is not available until after the report engine takes over and does the rendering. You can access/modify formula definitions before the report is rendered but have no access to the actual value calculated from code behind. Even if you add a blank subreport and add a parameter to it from the main report for the field value you are trying to access it will not have a value before the reports engine renders it. You should definitely look for a way to pull it from the data you are binding the report with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does Remember the Milk's string matching work? I'm interested in developing a similar solution to RTM's Smart Add Feature. For those who don't know Remember the Milk here's how it works: Adding tasks is done by means of an input box that accepts strings and parses out different parameters like task name, due date, priority, tags, etc. The parameters are usually preceded by special symbols ( ^, #, &, etc. ). RTM also accepts variations like 'Tennis on Wednesday'. My basic question to you is how would you design a system that is capable of intelligently discerning different parts of a string. Will I have to look into natural language processing? Thus far I'm using a simple regex expression that looks for special preceding symbols ( ^, #, &, etc. ) and then parses out the different parts of the string. This gets increasingly difficult with more and more unordered parameters. maybe that stems from my lack of regex expertise. A similar problem arises when trying to convert different formats of due dates ( '27 May 2008 16:00', '27th May 2008', '16th June 16:00', 'June 16th 12:00', 'today 12:00am', etc) into datetime objects. I'm currently using Python and regular expressions. My method is to basically run through a long list of possible date and time combinations and convert the matching expression with date.strptime. I found this approach to be hard to maintain; lots of false positives, leftover strings etc. You can look at my code here: https://gist.github.com/1233786 It's not pretty, you have been warned. I'd appreciate any hint into the right direction to approach this topic. Coding a dateparser was really fun but I before I hunt down all the bugs in hundreds of different use cases I thought I check if there's a more elegant design pattern. P.S.: I would love some code samples to sink my teeth in. Preferably Python :) A: I assume they have some grammars for parsing input sentece. Those grammar can express variety of NLP structures, such es entity extraction. For those grammar one can use GATE JAPE(http://gate.ac.uk/sale/tao/splitch8.html#chap:jape) or Gexp(http://code.google.com/p/graph-expression/)
{ "language": "en", "url": "https://stackoverflow.com/questions/7508487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When should the dimens.xml file be used in Android? For instance, in a specific layout I have the following XML: <GridView android:id="@+id/gridView1" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="3dp" android:columnWidth="48dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="spacingWidth" /> This grid view is specific to this layout and I don't think I'll be using any other grid views with similar properties. That to say that the dimension values in the code are specific to that grid view. Should I still move them to a dimens.xml file or it's fine to just leave them like that? If so, should I place values in the dimens.xml file only when that value is used across multiple layouts? A: The dimens.xml file is used to keep all the hard-coded pixel values in one place. Now, although you may not repeatedly use these values right now, it's still a good idea to to place them in dimens.xml for future reference. Besides, following a standard Android programming paradigm helps other developers to understand your code faster. This is much like the strings.xml where we place Strings some of which end up being used only once! :) A: I drop dimension values into a dimens.xml resource typically for three reasons: * *Reuse: I need multiple widgets or layouts to use the same value and I only want to change it once when updating or tweaking across the application. *Density Difference: If I need the dimension to be slightly smaller or larger from ldpi -> hdpi or small -> large. *Reading in from code: When I'm instantiating a view in the code and want to apply some static dimensions, putting them in dimens.xml as dp (or dip) allowing me to get a scaled value in Java code with Resources.getDimensionPixelSize(). A: Supplemental answer @Devunwired lists 3 reasons to use dimens.xml. Here are the details of how to do that. 1. Reuse If you set some dp or sp value in dimens.xml once like this <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="textview_padding">16dp</dimen> <dimen name="large_text_size">30sp</dimen> </resources> you can reuse it throughout your app in multiple locations. <TextView android:padding="@dimen/textview_padding" android:textSize="@dimen/large_text_size" ... /> <TextView android:padding="@dimen/textview_padding" android:textSize="@dimen/large_text_size" ... /> Then when you need to make a change, you only need to do it in one place. Notes * *This is basically the same effect as using a style or theme. *Be careful not to give two different views the same dimen value if they really shouldn't be. If you need to make changes to one set of views but not another, then you will have to go back to each one individually, which defeats the purpose. 2. Size Difference * *@Devunwired called this Density difference, but if you are using dp (density independent pixels), this already takes care are the density difference problem for all but the most minor cases. So in my opinion, screen size is a more important factor for using dimens.xml. An 8dp padding might look great on a phone, but when the app is run on a tablet, it looks too narrow. You can solve this problem by making two (or more) different versions of dimens.xml. Right click your res folder and choose New > Value resource file. Then write in dimens and choose Smallest Screen Width. Write in 600 for the width (7” tablet). (There are other ways of choosing the sizes. See the documentation and this answer for more.) This will make another values folder that will be used for devices whose smallest screen width is 600dp. In the Android view the two dimens.xml files look like this. Now you can modify them independently. values/dimens.xml <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="my_default_padding">16dp</dimen> </resources> values-sw600dp/dimens.xml <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="my_default_padding">64dp</dimen> </resources> When using your dimen you only have to set it with the name you used in both dimens.xml files. <LinearLayout ... android:padding="@dimen/my_default_padding"> </LinearLayout> The system will automatically choose the right value for you depending on the device the user is using. 3. Reading in from code Sometimes it is a pain scaling programmatically between px and dp (see this answer for how). If you have a fixed dp value already defined in dimens.xml like this <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="my_dp_value">16dp</dimen> </resources> Then you can easily get it with int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_dp_value); and it will already be converted to pixels for whatever density device the user has. A: I don’t know if it can help you but I wrote a little java programe that allows you to duplicate a dimension xml file with a new desired value so that you no longer have to do it by hand line by line. https://github.com/Drex-xdev/Dimensions-Scalable-Android
{ "language": "en", "url": "https://stackoverflow.com/questions/7508493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: jquery, trying to bind event to tr but it's also applied to child elements I'm trying to add a row click event on a table populated by json data. The row click itselves works but it's also applied to child elements such as checkboxes and buttons which are in the row cells. $('#results tbody tr').live("click",function(){     }); That's the way i'm selecting the table row, maybe i'm missing something very obvious here? Probably! Thanks for your time! regards, Mark A: Basically, if you don't handle the clicks coming from the sub-elements (or cancel their propagation) they will bubble up to the tr Either do something to return false; on sub-element clicks to stop the event propagation, or view the event coming in to your function above, an see what triggered it, if it was a sub-element, ignore it. A: Prevent input and checkbox click events from bubbling up. $('#results tbody tr:input', '#results tbody tr:checkbox').live("click",function(event){ event.stopPropagation(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7508494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tumblr RSS feed set max results? Does anyone know a way to do this.. I searched their API and came up blank http://www.tumblr.com/docs/en/developers I was using blogger before and was able to set the results like this blogspot.com/feeds/posts/default?max-results=1000 thanks A: Here is the answer straight from Tumblr's tech support (it's no) Tess, Sep-22 09:54 (EDT): I'm sorry, but that isn't supported at this time. My apologies. Tess -- Tumblr Support support@tumblr.com Sam Saccone, Sep-21 21:14 (EDT): hello, I requested an rss feed only to find that it was limited at 20 results is there a way to get all the results?
{ "language": "en", "url": "https://stackoverflow.com/questions/7508495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a subclass in Eclipse? During lecture, my professor very quickly created a subclass in Eclipse. The result has the "extend" keyword added to the subclass. I didn't see what buttons he clicked. Does anyone know where should I click? (I think he right clicked on the current class in the package explorer, then New ==> class, then I'm lost on what to select). A: When you are viewing the class you want to subclass, open Type Hierarchy (press F4). Right click on the parent-to-be class, and in the menu go to new -> class ( or Ctrl-n , class ). A: Please see the picture where to enter your existing super class A: Right click on project name on Package Explorer + Add New Class + Type package Name, Name (sub-class name), and Super class (or Click on Browse to choose super class). A: You can try to bind Keys for New (New Wizard: Class) command (for eg.: Ctrl + Alt + N) by open Window> Preferences > General > Keys. And then, on new wizard window, change the Superclass box. Hth. A: Rt click on class > Show in Package Explorer Ctrl-N > Class The selected class will be automatically populated as the super class and you can enter you class name to derive from that A: When you create a class, replace the name of superclass with the your superclass name, that will do the job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: silverlight Binding from VM collection to View not working need some help I know I am missing something here and I could use a pointer. Within a project I have an expander control when this control is clicked it makes a RIA call to a POCO within my project to retreive a second set of data. I am using the SimpleMVVM toolkit here so please let me know if I need to expand on any additional areas. Within the xaml the expander is laid out as <toolkit:Expander Header="Name" Style="{StaticResource DetailExpanderSytle}" > <i:Interaction.Triggers> <i:EventTrigger EventName="Expanded"> <ei:CallMethodAction TargetObject="{Binding Source={StaticResource vm}}" MethodName="showWarrantNameDetail"/> </i:EventTrigger> </i:Interaction.Triggers> <StackPanel Orientation="Vertical"> <sdk:DataGrid AutoGenerateColumns="true" ItemsSource="{Binding NameResult}" AlternatingRowBackground="Gainsboro" HorizontalAlignment="Stretch" MaxHeight="200"> </sdk:DataGrid> <local:NameContainer DataContext="{Binding}" /> </StackPanel> </toolkit:Expander> I am using the expression Dll coupled with Simple MVVM to get at the methods in the view model vs commands. Within the view model I have the following code public void showWarrantNameDetail() { //set flags IsBusy = true; CanDo = false; EntityQuery<WarrantNameDataView> query = App.cdContext.GetWarrantNameDataViewsQuery().Where(a => a.PrimaryObjectId == Convert.ToInt32(RecID)); Action<LoadOperation<WarrantNameDataView>> completeProcessing = delegate(LoadOperation<WarrantNameDataView> loadOp) { if (!loadOp.HasError) { processWarrantNames(loadOp.Entities); } else { Exception error = loadOp.Error; } }; LoadOperation<WarrantNameDataView> loadOperation = App.cdContext.Load(query, completeProcessing, false); } private void processWarrantNames(IEnumerable<WarrantNameDataView> entities) { ObservableCollection<WarrantNameDataView> NameResult = new ObservableCollection<WarrantNameDataView>(entities); //we're done IsBusy = false; CanDo = true; } When I set a break on the processWarrantName I can see the NameResult is set to X number of returns. However within the view the datagrid does not get populated with anything? Can anyone help me understand what I need to do with the bindings to get the gridview to populate? Other areas of the form which are bound to other collections show data so I know I have the data context of the view set correctly. I've tried both Data context as well as Items Source and no return? When I set a break on the code the collection is returned as follows so I can see that data is being returned. Any suggestions on what I am missing I would greatly appreciate it. With regards to the page datacontext I am setting it in the code behind as follows: var WarrantDetailViewModel = ((ViewModelLocator)App.Current.Resources["Locator"]).WarrantDetailViewModel; this.DataContext = WarrantDetailViewModel; this.Resources.Add("vm", WarrantDetailViewModel); Thanks in advance for any suggestions. A: Make ObservableCollection<WarrantNameDataView> NameResult a public property of your ViewModel class. Your view will not be able to bind to something that has a private method scope (or public method scope, or private member scope). //declaration public ObservableCollection<WarrantNameDataView> NameResult { get; set } //in the ViewModel constructor do this NameResult = new ObservableCollection<WarrantNameDataView>(); //then replace the original line in your method with: //EDIT: ObservableCollection has no AddRange. Either loop through //entities and add them to the collection or see OP's answer. //NameResult.AddRange(entities); If processWarrantNames gets called more than once, you might need to call NameResult.Clear() before calling AddRange() adding to the collection. A: Phil was correct in setting the property to public. One note I'll add is there is no AddRange property in SL or ObservableCollection class that I could find. I was able to assign the entities to the OC using the following code private ObservableCollection<WarrantNameDataView> warrantNameResult; public ObservableCollection<WarrantNameDataView> WarrantNameResult { get { return warrantNameResult; } set { warrantNameResult = value; NotifyPropertyChanged(vm => vm.WarrantNameResult); } } and then within the return method WarrantNameResult = new ObservableCollection<WarrantNameDataView>(entities); This worked and passed to the UI the collection of data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to transfer MemoryStream via WCF Streaming I am planning to pass MemoryStream via WCF Streaming but it seems not working but when I slightly change the code to pass FileStream instead, it is working. In fact, my purpose is to pass large collection of business objects (serializable). I am using basicHttpBinding. Your suggestion would be much appreciated! Edited: The symptoms of the issue is that the incoming stream is empty. There is neither error nor exception. A: You're not providing many details, however, I'm almost certain I know what the issue is as I've seen that happening a lot. If you write something to a MemoryStream in order to return that one as the result of a WCF service operation, you need to manually reset the stream to its beginning before returning it. WCF will only read the stream from it current position, hence will return an empty stream if that position hasn't been reset. That would at least explain the problem you're describing. Hope this helps. Here some sample code: [OperationContract] public Stream GetSomeData() { var stream = new MemoryStream(); using(var file = File.OpenRead("path")) { // write something to the stream: file.CopyTo(stream); // here, the MemoryStream is positioned at its end } // This is the crucial part: stream.Position = 0L; return stream; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7508502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Passing multiple arguments to a thread from a structure I'm having problems passing the arguments, using a structure containing another structure i know there's something wrong with the way i'm using the structures but i just cant see where... Thanks! this is my struct typedef struct { IMAGE *imagenfte; IMAGE *imagendst; }thread_data; //thread_data *data = (thread_data *) malloc(sizeof(thread_data)); this is the other structure typedef struct { HEADER header; INFOHEADER infoheader; PIXEL *pixel; } IMAGE; IMAGE imagenfte,imagendst; this is my thread function void *processBMP2(void *argumentos) { thread_data *my_data; my_data = (thread_data *) (argumentos); IMAGE *imagefte, *imagedst; imagefte = my_data->imagenfte; imagedst = my_data->imagendst; free(my_data); int i,j; int count=0; PIXEL *pfte,*pdst; PIXEL *v0,*v1,*v2,*v3,*v4,*v5,*v6,*v7; int imageRows,imageCols; memcpy(imagedst,imagefte,sizeof(IMAGE)-sizeof(PIXEL *)); imageRows = imagefte->infoheader.rows; imageCols = imagefte->infoheader.cols; imagedst->pixel=(PIXEL *)malloc(sizeof(PIXEL)*imageRows*imageCols); ... and this is the way i`m creating the thread and passing de arguments pthread_t hilo; thread_data *my_data = (thread_data *) malloc(sizeof(thread_data)); my_data->imagenfte = &imagenfte; my_data->imagendst = &imagendst; pthread_create(&hilo,NULL, processBMP2, my_data); //processBMP(&imagenfte,&imagendst); A: What you're doing is exactly right. The new thread needs to be the one responsible for freeing the memory because the parent thread cannot know when the new thread is done accessing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compilation warning for void ** and void * I have a question regarding void* and void** and I know this is sort of an old question and has been asked (somewhat) before in stackoverflow. So the question is the following: When I compile this code with gcc 4.4.3 under ubuntu 10.10, I get the following warning: zz.c: In function ‘main’: zz.c:21: warning: passing argument 1 of ‘bar’ from incompatible pointer type zz.c:9: note: expected ‘void **’ but argument is of type ‘float **’ why is it that its ok to pass variable x as an argument of foo() but its not ok to pass variable y as an argument of bar(). I can fix this by explicitly casting both variables into void* and void** as expected. void foo (void* a){ } void bar(void **a){ *a = (float *) malloc(100*sizeof(float)); } int main (){ float *x = (float*) malloc(100*sizeof(float)); foo(x); free(x); float *y; bar(&y); free(y); return 0; } A: The C++ standard allows for any pointer to be implicitly converted to a void*. But a void** is not the same thing as a void*; it is a pointer to a void*. Therefore, it falls under the rules for regular pointer conversions (ie: forbidden without a cast, with some exceptions). A: Adding to the information in the other answers, void* acts as a generic pointer type in C. There are things that are generic about it: any pointer (other than a pointer-to-function type) can be converted to void* and back again without loss of information, and a pointer expression (again, other than pointer-to-function) can be implicitly converted to void*. (C++ has slightly different rules.) You might think that void** is a generic pointer-to-pointer type, but it isn't. It's a pointer to a specific type, namely to void*. In fact, C doesn't have a generic pointer-to-pointer type. But it does have a generic pointer type, so any code that tries to use void** as a generic pointer-to-pointer type can probably just use void* instead. A: void *a means that a points to an object of unknown type. However, a itself is not an unknown type because a is known to have type void*. Only the object that a points to has an unknown type. void **a means that a points to an object of type void*. The object that *a points to has an unknown type, but the object *a itself is a pointer with type void*. &y is a pointer to an object of type float*. &y is not a pointer to an object of type void*.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: default(T) on reflected type In browsing other answers, I have come up with the following extension method which works a treat: public static T Convert<T>( this string input ) { var converter = TypeDescriptor.GetConverter( typeof( T ) ); if ( converter != null ) { try { T result = (T) converter.ConvertFromString( input ); return result; } catch { return default( T ); } } return default( T ); } And I can use it like: string s = "2011-09-21 17:45"; DateTime result = s.ConvertTo( typeof( DateTime ) ); if ( result == DateTime.MinValue ) doSomethingWithTheBadData(); Awesome! Works great. Now, I'd like to do something similar with a reflected type. I have: public static dynamic ConvertTo( this string input, Type type ) { var converter = TypeDescriptor.GetConverter( type ); if ( converter != null ) { try { dynamic result = converter.ConvertFromString( input ); return ( result ); } catch { return default( type ); // bogus } } return default( type ); // bogus } And I'd like to use it thus: Type someType; // will be DateTime, int, etc., but not known until runtime DateTime result = s.ConvertTo( sometype ); if ( result == DateTime.MinValue ) doSomethingWithTheBadData(); Of course, the compiler objects to the 'bogus' lines in the ConvertTo method. What I need (ok, don't necessarily need, but it'd be nice) is a way to get the same result as in the first example so that if the conversion fails, something that can be assigned to the reflected object is returned and can be recognized in the same manner as in the first example. Edit: What I finished with: public static dynamic ConvertTo( this string input, Type type, out bool success ) { dynamic result; var converter = TypeDescriptor.GetConverter( type ); if ( converter != null ) { try { result = converter.ConvertFromString( input ); success = true; return result; } catch { /* swallow the exception */ } } result = type.IsValueType ? Activator.CreateInstance( type ) : null; success = false; return result; } and used: bool success; string val = "2011-09-21 17:25"; dateTime = val.ConvertTo( typeof( DateTime ), out success ); if ( success ) doSomethingGood(); val = "foo"; dateTime = val.ConvertTo( typeof( DateTime ), out success ); if ( !success ) dealWithBadData(); Remembering that, for the purpose of demonstration, I'm hard-coding the typeof() bit. In my application, the types are all reflected. Thanks to all for the speedy answers! A: You can use //to get default(T) from an instance of Type type.IsValueType ? Activator.CreateInstance(type) : null; This is because value types are guaranteed to have a default constructor, and the default value of a reference type is a null. A: If you're passing in the type using typeof(Type), then obviously you could just use the first method. Assuming, then, that you're getting the type via reflection (which you say you are) then you can also use reflection to get the MethodInfo for your first version of Convert(), and then use MakeGenericMethod() to substitute your reflected type into it: MethodInfo m = typeof(MyConvertExtensions).GetMethod("Convert"); MethodInfo invocable = m.MakeGenericMethod(myReflectedType); invocable.Invoke(null, new[] { myString }); A: Untested, but maybe something like this? public static dynamic ConvertTo(this string input, Type type) { var converter = TypeDescriptor.GetConverter(type); if (converter != null) { try { return converter.ConvertFromString(input); } catch { // ignore } } if (type.IsValueType) return Activator.CreateInstance(type); return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7508505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is a ASP.NET MVC controller action faster/more efficient than a HttpHandler? I'm trying to create a simple lightweight server side redirect which inspects the client's User-Agent and redirects to a website for a given browser. For example: if(Request.UserAgent.contains("Firefox") { //redirect to www.yahoo.com } else if(Request.UserAgent.contains("Safari") { //redirect to www.google.com } else { // redirect to www.msn.com } What would be the most performant/efficient way of accomplishing this using asp.net? A: No. Controllers implement IHttpHandler behind the scenes and use reflection to execute action methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: scaling UIScrollView contentSize to fit UIView with variable-height UITableView inside I have a uiview with a uiscrollview as a subview in a nib. Then, I load another uiview with a uitableview as a subview of this other uiview (among other elements inside this view) as a subview of the uiscrollview. That is, UISCrollView -> UIView -> UITableView (and some other views inside the UIView). And I need to do the following: Once I know the final height of the tableview (depending on the number of cells and height of them) I need to resize the uiview containing it and, in turn, resize the contentSize property of the containing scrollview. But I don't know at which point the final size of the tableview is known (because it can dynamically change size depending on the amount of text its cells will hold) and neither do I know by how much will the tableview exceed the uiview (which by default is 320 x 460). I've tried setting the view containing the tableview to a height of 900 on viewdidload and setting it to sizeToFit, hoping it would shrink as tablecells are added to the tableview (assuming as cells are added the tableview's frame would scale appropriately). But this doesn't seem to work. Any thoughts? Thanks! A: I just ran into a similar situation (UIScrollView -> UITableView) and was banging my head against it for hours. The short answer is this: the correct sizes to use as the basis of sizing things out were not available until my ViewController (governing the UIScrollView) was sent viewWillAppear:. Before then, I found that the values were set, but often wrong. (E.g., my first attempt at doing this was in viewDidLoad:, and the sizing values were changed there, but they were wrong!) So my solution was thus: * *In viewDidLoad: cause your enclosed UITableView to reloadData once you have your data in place. *in viewWillAppear: do the following (presuming tableView is the enclosed UITableView and scrollView is the enclosing UIScrollView): tableView.frame = (CGRect){ tableView.frame.origin, tableView.contentSize }; // Finally, set content size based on the last element in the scrollView // in my case, the last element IS the tableView, yours might be different scrollView.contentSize = CGSizeMake(scrollView.width - scrollView.contentInset.left - self.scrollView.contentInset.right, tableView.top + tableView.height); N.B., I was getting some very weird numbers when I checked them before viewWillAppear:; e.g., the tableView.contentSize seemed to be the product of default rowHeight * number of rows, ignoring my custom row heights and excluding any separators! Very odd. A: This is just a guess, but since UITableView is a subclass of UIScrollView, can you use the contentSize property to see its overall size after a call to reloadData? You could use the size of the tableview to resize the UIView and the contentSize of the scrollView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: strcpy() causes segmentation fault? Possible Duplicate: Getting Segmentation Fault Why does this code cause a segmentation fault? char *text = "foo"; strcpy(text, ""); As far as I understand it, the first line allocates some memory (to hold the string "foo") and text points to that allocated memory. The second line copies an empty string into the location that text points to. This code might not make a lot of sense, but why does it fail? A: Whenever you have a string literal (in your case, "foo"), the program stores that value in a readonly section of memory. strcpy wants to modify that value but it is readonly, hence the segmentation fault. Also, text should be a const char*, not a char*. A: Because a string literal (like "foo") is read-only. A: Because the string literals are stored in the read only region of memory. Thus attempting the modification of foo(using strcpy in this case) is an undefined behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC get URL index value after jquery call Hi have an MVC page that shows up with the url like: http://myhost/Invoice/Edit/2 When I'm at this page I run some jquery that calls another method in the controller. In this new method I want to get the 2 from http://myhost/Invoice/Edit/2. One problem is now that I've called the new method the Request.Url has obviously changed from http://myhost/Invoice/Edit/2 to be different. Can anyone tell me in this situation how I would get the 2? A: I run some jquery that calls another method in the controller. You haven't shown how exactly this script is calling your other controller action but you should pass the initial id as parameter to this action. For example if you were doing an AJAX call or something: $.post('@Url.Action("Edit")', new { invoiceId = '@Model.Id' }, function() { ... }); and in the controller action: [HttpPost] public ActionResult Edit(int invoiceId) { ... } A: ControllerContext.ParentActionViewContext.RouteData.Values["id"]
{ "language": "en", "url": "https://stackoverflow.com/questions/7508531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: efficient computation of Trace(AB^{-1}) given A and B I have two square matrices A and B. A is symmetric, B is symmetric positive definite. I would like to compute $trace(A.B^{-1})$. For now, I compute the Cholesky decomposition of B, solve for C in the equation $A=C.B$ and sum up the diagonal elements. Is there a more efficient way of proceeding? I plan on using Eigen. Could you provide an implementation if the matrices are sparse (A can often be diagonal, B is often band-diagonal)? A: If B is sparse, it may be efficient (i.e., O(n), assuming good condition number of B) to solve for x_i in B x_i = a_i (sample Conjugate Gradient code is given on Wikipedia). Taking a_i to be the column vectors of A, you get the matrix B^{-1} A in O(n^2). Then you can sum the diagonal elements to get the trace. Generally, it's easier to do this sparse inverse multiplication than to get the full set of eigenvalues. For comparison, Cholesky decomposition is O(n^3). (see Darren Engwirda's comment below about Cholesky). If you only need an approximation to the trace, you can actually reduce the cost to O(q n) by averaging r^T (A B^{-1}) r over q random vectors r. Usually q << n. This is an unbiased estimate provided that the components of the random vector r satisfy < r_i r_j > = \delta_{ij} where < ... > indicates an average over the distribution of r. For example, components r_i could be independent gaussian distributed with unit variance. Or they could be selected uniformly from +-1. Typically the trace scales like O(n) and the error in the trace estimate scales like O(sqrt(n/q)), so the relative error scales as O(sqrt(1/nq)). A: If generalized eigenvalues are more efficient to compute, you can compute the generalized eigenvalues, A*v = lambda* B *v and then sum up all the lambdas.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Detect if browser is buffering audio stream from mixcloud My app embeds mixcloud's player widget. It's an embedded swf. <object> <embed src="http://www.mixcloud.com/media/swf/player/mixcloudLoader.swf?feed=x"> </embed> </object> If audio is presently streaming, then I want to alert any user who might click on one of my site's internal navigation links that the buffer will be lost if they continue. Is there a way to detect whether or not the browser is buffering (or has finished buffering) a particular stream? I think I need to distinguish between the objects that initialize the player (on page load), and the actual audio itself so that this alert only appears if the user has something playing or buffering. Is there a js library that can help me here?
{ "language": "en", "url": "https://stackoverflow.com/questions/7508535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook API I get "Method Not Implemented" error, but it works if i put the url in a browser When I call https://graph.facebook.com/oauth/access_token I keep getting a return string that says “methed not iomplamented” I’m calling it in php as follows file_get_contents("https://graph.facebook.com/oauth/access_token?my_ap_id&redirect_uri=http://www.besttechsolutions.biz/projects/facebook/index.phpclient_secret=MySecret458d628b1af&code=".$code); I get Method Not Implemented Invalid method in request, If I put the url in a browser, it worcks returning the code. Why does it work in the browser, but not when I used the file_get_contents function???? A: I think your PHP function is doing a POST instead of a GET. That's what Method Not Implemented usually means, that you're doing the wrong one. When you put it in your browser it does a GET.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: TabHost shows default Activity after showing new activity for a while Thanks for reading. I am facing a problem where when I start a new Activity in my TabHost, the new Activity only shows up for a few seconds before returning to the default Activity in that Tab. I am using the TabHost for laying out 5 tabs in my app. In one of the tabs, I start a new Activity as follows: Intent intent = new Intent(this, NewActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); LocalActivityManager manager = MyActivityGroup.ActivityGroup.getLocalActivityManager(); MyActivityGroup.ActivityGroup.replaceView(manager.startActivity("NewActivity", intent).getDecorView() ); In this NewActivitys' onCreate(), I am calling a speech recognition libraries' startRecord() method which is implemented as follows: private void startRecognition() { try { recognizer.startRecord(new SpeechRecognizerEvent() { @Override public void onRecognitionComplete(SpeechResult result) { //get result data } } All I know is there is a SpeechFrameworkActivity associated with this library in the AndroidManifest.xml. If I comment out calling the startRecord() method, the NewActivity does not disappear and continues to show. I am just clueless about what is going wrong. From the logs, all I see is this one line: 09-21 21:16:44.860: DEBUG/PhoneWindow(6737): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView@4794d9b8 has no id. I tried using onConfigurationChanged() in my MainTabActivity but that didn't solve the problem. Please help! Any help/pointers would be great appreciated! A: this may happen due to less memory in my case i clear the memory every time before using and it work may be in ur case it works or use system.gc or clear buffer just try this if it helps u .
{ "language": "en", "url": "https://stackoverflow.com/questions/7508543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to enable YSlow in Firefox? I have installed the latest versions of YSlow and Firebug into the latest version of Firefox on Windows 7 (and restarted Firefox), but when I click on YSlow nothing happens. Also, when I click on Firebug, it opens but has no YSlow tab. I have disabled all other Firefox plugins and played with right-clicking YSlow and clicking run once and auto-run. What am I doing wrong? A: As a temporary solution, try using the YSlow bookmarklet. It's an equivalent of regular YSlow. A: Try running Firefox in Safe Mode and disable other plugins that may conflict with YSlow. Also ensure you have really restarted Firefox. A: YSlow seems to have got broken inside firebug extension in latest firefox release as evident from this tweet from their official twitter handle. Try using GTMetrix google chrome extension. It provides one of the most exhaustive web performance statistics using PageSpeed and ySlow both. Below I've mentioned google chrome store extension link. The only thing is that you will have to use chrome instead of firefox as your web browser. https://chrome.google.com/webstore/detail/gtmetrix-plugin/maaoaegejdlcdijmlfmpmeknliggkfdm
{ "language": "en", "url": "https://stackoverflow.com/questions/7508548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Different results from Dijkstra algorithms I am working from Programming Game AI by Example book. Look at this image, the result on the left is the author's, the one on the right is mine. Green is source and red is target. Dijkstra is applied, and you can see the shortest path but also the other paths that were searched. How come my image is different, what could this mean? A: It seems that you just used different tiebreakers when selecting the next square. From what I see you searched the same squares in the same amount of time, but in the part where you arbitrarily pick the next square to search, you chose differently. A: At a very quick glance it looks like they weight diagonal walks heavier then vertical or horizontal ones. Yours looks like it weighs going n,s,w,e,ne,nw,se,sw all the same. Hence you go diagonal when they went horizontal or vertical.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: BackboneJS: Map RESTful URL to old-school HTTP Query URL I've just picked up BackboneJS for a work experiment. We are implementing a whole slew of web-apps on our platform so using a JS framework would simplify a lot of stuff. However, the way to query the server is to use regular HTTP query strings appended to back of a script name; for example, getSomething?id=0&name=2. Basically I am wondering if it is possible in backbone (or, if someone can recommend another popular framework, that one) to map something like /getSomething/:id/:name to the HTTP query string basically making it /service/rest/getSomething?id=:id&name=:name. Any help is appreciated. Thanks. A: Backbone doesn't actually require you to use REST and the like with its models. If you decide to skip that, they still offer the ability for you to update models using the .set() to assign a new set of values you retrieve via another method. I've actually got several models where I may hit .fetch() on the model, but it will perform one or several calls to the server to get data and set it back onto the model. Our back end services just don't happen to be a nice fit to the sync setup backbone expects for its built in saving and fetching of models. Small clarification: I should say that what I've done here is override the "fetch" function on my models with an alternate implementation that uses jQuery $.ajax() calls. I'm not sure about the whole question you asked originally though with respect to mapping URLs. The URLs that the Backbone router takes are pulled apart and you get the individual pieces. I wouldn't anticipate the router ever making a direct call to the back end though, I would expect that the router would pass those through to a call on the model, which would then interface with the service to get data. Thus only the model layer sees the backend details of the services and any data mapping necessary, the router and the views stay clean of those kind of details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to enable scrolling of content inside a modal? I'm trying to fit a lot of text into a modal box created using Twitter Bootstrap, but I'm having a problem: that content refuses to scroll. I tried adding overflow:scroll and overflow-y:scroll, but to no avail; that merely causes it to display a scroll bar without actually enabling the scrolling. What's the cause behind that and what can I do? A: Set height for modal-body and not for the whole modal to get a perfect scroll on modal overlay. I get it work like this: .MyModal { height: 450px; overflow-y: auto; } Here you can set height as per your requirements. A: In Bootstrap.css change the background attribute (position) of Modal from fixed to absolute A: In Bootstrap 3 you have to change the css class .modal before (bootstrap default) : .modal { overflow-y: auto; } after (after you edit it): .modal { overflow-y: scroll; } A: This is how I did it purely with CSS overriding some classes: .modal { height: 60%; .modal-body { height: 80%; overflow-y: scroll; } } Hope it helps you. A: If I recall correctly, setting overflow:hidden on the body didn't work on all the browsers I was testing for a modal library I built for a mobile site. Specifically, I had trouble with preventing the body from scrolling in addition to the modal scrolling even when I put overflow:hidden on the body. For my current site, I ended up doing something like this. It basically just stores your current scroll position in addition to setting "overflow" to "hidden" on the page body, then restores the scroll position after the modal closes. There's a condition in there for when another bootstrap modal opens while one is already active. Otherwise, the rest of the code should be self explanatory. Note that if the overflow:hidden on the body doesn't prevent the window from scrolling for a given browser, this at least sets the original scroll location back upon exit. function bindBootstrapModalEvents() { var $body = $('body'), curPos = 0, isOpened = false, isOpenedTwice = false; $body.off('shown.bs.modal hidden.bs.modal', '.modal'); $body.on('shown.bs.modal', '.modal', function () { if (isOpened) { isOpenedTwice = true; } else { isOpened = true; curPos = $(window).scrollTop(); $body.css('overflow', 'hidden'); } }); $body.on('hidden.bs.modal', '.modal', function () { if (!isOpenedTwice) { $(window).scrollTop(curPos); $body.css('overflow', 'visible'); isOpened = false; } isOpenedTwice = false; }); } If you don't like this, the other option would be to assign a max-height and overflow:auto to .modal-body like so: .modal-body { max-height:300px; overflow:auto; } For this case, you could configure the max-height for different screen sizes and leave the overflow:auto for different screen sizes. You would have to make sure that the modal header, footer, and body don't add up to more than the screen size, though, so I would include that part in your calculations. A: When using Bootstrap modal with skrollr, the modal will become not scrollable. Problem fixed with stop the touch event from propagating. $('#modalFooter').on('touchstart touchmove touchend', function(e) { e.stopPropagation(); }); more details at Add scroll event to the element inside #skrollr-body A: This answer actually has two parts, a UX warning, and an actual solution. UX Warning If your modal contains so much that it needs to scroll, ask yourself if you should be using a modal at all. The size of the bootstrap modal by default is a pretty good constraint on how much visual information should fit. Depending on what you're making, you may instead want to opt for a new page or a wizard. Actual Solution Is here: http://jsfiddle.net/ajkochanowicz/YDjsE/2/ This solution will also allow you to change the height of .modal and have the .modal-body take up the remaining space with a vertical scrollbar if necessary. UPDATE Note that in Bootstrap 3, the modal has been refactored to better handle overflowing content. You'll be able to scroll the modal itself up and down as it flows under the viewport. A: Actually for Bootstrap 3 you also need to override the .modal-open class on body. body.modal-open, .modal-open .navbar-fixed-top, .modal-open .navbar-fixed-bottom { margin-right: 15px; /*<-- to margin-right: 0px;*/ } A: I'm having this issue on Mobile Safari on my iPhone6 Bootstrap adds the class .modal-open to the body when a modal is opened. I've tried to make minimal overrides to Bootstrap 3.2.0, and came up with the following: .modal-open { position: fixed; } .modal { overflow-y: auto; } For comparison, I've included the associated Bootstrap styles below. Selected extract from bootstrap/less/modals.less (don't include this in your fix): // Kill the scroll on the body .modal-open { overflow: hidden; } // Container that the modal scrolls within .modal { display: none; overflow: hidden; position: fixed; -webkit-overflow-scrolling: touch; } .modal-open .modal { overflow-x: hidden; overflow-y: auto; } Mobile Safari version used: User-Agent Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B411 Safari/600.1.4 A: I had the same issue, and found a fix as below: $('.yourModalClassOr#ID').on('shown.bs.modal', function (e) { $(' yourModalClassOr#ID ').css("max-height", $(window).height()); $(' yourModalClassOr#ID ').css("overflow-y", "scroll"); /*Important*/ $(' yourModalClassOr#ID ').modal('handleUpdate'); }); 100% working. A: .modal-body { max-height: 80vh; overflow-y: scroll; } it's works for me A: After using all these mentioned solution, i was still not able to scroll using mouse scroll, keyboard up/down button were working for scrolling content. So i have added below css fixes to make it working .modal-open { overflow: hidden; } .modal-open .modal { overflow-x: hidden; overflow-y: auto; **pointer-events: auto;** } Added pointer-events: auto; to make it mouse scrollable. A: Bootstrap will add or remove a css "modal-open" to the <body> tag when we open or close a modal. So if you open multiple modal and then close arbitrary one, the modal-open css will be removed from the body tag. But the scroll effect depend on the attribute "overflow-y: auto;" defined in modal-open A: I was able to overcome this by using the "vh" metric with max-height on the .modal-body element. 70vh looked about right for my uses. .modal-body { overflow-y: auto; max-height: 70vh; } A: In Bootstrap 5, do it with classes: change <div class="modal-dialog"> to <div class="modal-dialog modal-dialog-scrollable"> Also, consider adding class modal-dialog-centered . A: In Bootstrap v3.3.7 I needed to add the following to allow horizontal scrolling: .modal-open { overflow: visible; } .modal { position: absolute; } .modal.in { display: table !important; } A: Solution 1: You can declare .modal{ overflow-y:auto} or .modal-open .modal{ overflow-y:auto} if you are using below 3v of bootstrap (for upper versions it is already declared). Bootstrap adds modal-open class to body in order to remove scrollbars in case modal is shown, but does not add any class to html which also can have scrollbars, as a result the scrollbar of html sometimes can be visible too, to remove it you have to set modal show/hide events and add/remove overflow:hidden on html. Here how to do this. $('.modal').on('hidden.bs.modal', function () { $('html').css('overflow','auto'); }).on('shown.bs.modal', function () { $('html').css('overflow','hidden'); }); Solution 2: As modal has functionality keys, the best way to handle this is to fix height of or even better connect the height of modal with height of the viewport like this - .modal-body { overflow:auto; max-height: 65vh; } With this method you also do not have to handle body and html scrollbars. Note 1: Browser support for vh units. Note 2: As it is proposed above. If you change .modal{position:fixed} to .modal{position:absolute}, but in case page has more height than modal user can scroll too much up and modal will disappear from viewport, this is not good for user experience.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "75" }
Q: Display Notification when receiving C2DM message causes crash I want to display a message contained in my C2DM message's payload, but I can't seem to get this to work without crashing. package com.themenetwork.app; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class C2DMMessageReceiver extends BroadcastReceiver { public NotificationManager myNotificationManager; public static final int NOTIFICATION_ID = 1; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.w("c2dm", "Message Receiver called"); if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) { Log.w("c2dm", "Received message"); final String payload = intent.getStringExtra("payload"); Log.d("c2dm", "dmControl: payload = " + payload); Notification notification = new Notification(R.drawable.icon, "Hello", 0); Intent notificationIntent = new Intent(context, RootActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, "Title", "Text", contentIntent); notification.flags |= Notification.FLAG_ONGOING_EVENT; myNotificationManager.notify(NOTIFICATION_ID, notification); } } } The exception is... Thread [<1> main] (Suspended (exception RuntimeException)) ActivityThread.handleReceiver(ActivityThread$ReceiverData) line: 1881 ActivityThread.access$2400(ActivityThread, ActivityThread$ReceiverData) line: 124 ActivityThread$H.handleMessage(Message) line: 1018 ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 130 ActivityThread.main(String[]) line: 3806 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 507 ZygoteInit$MethodAndArgsCaller.run() line: 839 ZygoteInit.main(String[]) line: 597 NativeStart.main(String[]) line: not available [native method] I'm really new to Java, let alone Android, so I'm completely stumped as to why this isn't working. A: Isn't myNotificationManager null when you try to invoke notify on it? You need to initialize it to point to a valid instance of a NotificationManager, maybe like this: myNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
{ "language": "en", "url": "https://stackoverflow.com/questions/7508578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: google maps inside my Web Content Form within Master Page I am trying to add a simple Google Map to my Web Content Form (that uses a Master Page) but nothing is showing up and I'm not getting any noticeable errors <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="ShelterMap.aspx.cs" Inherits="ShelterExpress.ShelterMap" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> #map_canvas { height: 100% } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js "></script> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <div id="map_canvas" style="width:100%; height:100%"></div> <script type="text/javascript"> $(document).ready(function() { var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }); </script> </asp:Content> A: You need to set width and height explicity, instead of 100%. Remove <style></style> tag, and set <div id="map_canvas" style="width: 300px; height: 300px"> <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js "></script> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <div id="map_canvas" style="width: 300px; height: 300px"> </div> <script type="text/javascript"> $(document).ready(function () { var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }); </script> </asp:Content> A: The map is loading but you have a 0px height div once it has loaded because (without seeing because you didn't post master page code) I would imagine you have not set the html body tag to have a 100% height as well as the html tag. It gets confused and cannot figure its own height out therefore you end up with a zero height div where the map should be. Try setting the #map_canvas to have a fixed height (say 600px) or make both body & html attributes also have a 100% height css rule. Should fix the issue. A: <div id="map_canvas" style="position:absolute;top:0;bottom:0;left:0;right:0;"> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7508579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Access IB Object from Custom Class This is a silly beginner question but... If I have a custom subclass of NSTextView "SSTextView" that spawns from Interface Builder, how do I access the instance of my custom class that is actually in the interface from inside SSTextView.m? The overall goal, I guess, is to be able to call an instance method in SSTextView.m from another method in the file. I know that [self aMethod] only works for class methods. Now, I know I can do this from another class's implementation by using IBOutlet SSTextView *myTextView; and making the connections in Interface Builder, but it seems like an odd organizational paradigm that I wouldn't be able to put the methods that deal with my user interface text view in its own implementation. Thanks in advance. A: Did you actually tried [self aMethod]? If you are in an instance method of SSTextView, you should be able to call an other instance method of SSTextView using [self aMethod]. As self is a pointer to the current class instance. A: You've got this part backwards: I know that [self aMethod] only works for class methods. [self aMethod] is how you invoke an instance method on the current object. [MyClass aMethod] is how you invoke a class method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WinCE emulator shows Black Screen when trying to run I am new to WinCE. I am trying to build an WinCE 6.0 Image using platform builder. So I went Like this . * *Visual Studio 2005 >> Platform Builder >> OS Design *Avilable BSP : CEPC X86 *Custom Device *Actice sync and Cab File Insaller and *Finished. Build >> Build OSDesign . Make Runtime image . In Device's I choose "Windows CE device " and in Device option Kernal Service Map >> Device Emulator Debugger >> KdStub Now After building and creating image when I click Attach devive , it comes up and shows me a Black screen. Not sure what mistake I am doing . Packages I Installed : * *Visual Studio 2005 *Visual Studio 2005 Service Pack 1 *Visual Studio 2005 Service Pack 1 Update for Windows Vista (if applicable) *Windows Embedded CE 6.0 Platform Builder *Windows Embedded CE 6.0 SP1 (required if PB 6.0 Tools have been installed) *Windows Embedded CE 6.0 R2 *Windows Embedded CE 6.0 R3 *Windows Embedded CE 6.0 Cumulative Product Update Rollup Package (through 12/31/2010) *Windows Embedded CE 6.0 Monthly update August A: I think you haven't selected properly the BSP, currently I am using WinCE 7.0, but from what I remember you should select a BSP called: Device Emulator: ARMV4 - something similar should be for a x86 - CEPC design. For example on WinCE 7.0 you have a BSP called VCEPC - Virtual CEPC that can be loaded in Virtual PC. The reason is that you have different drivers, different bootloader, etc. A: I have a similar problem that is not solved yet but searching a documentation around you can check if the KITL option in the project properties is ENABLED. If it is then please try disabling it, rebuild the project and make new run-time image. I hope this helps you. My problem is listed here: Black screen after booting WinCE 6.0 A: Since solving the same problem I agree with Patrik. In my case it was the KITL Option. After I disabled this option, my composed image continued booting. This MS article helped me out of the problem: http://msdn.microsoft.com/en-us/library/aa289160(v=vs.71).aspx#grfvsdtroubleshooting Section "Emulator generated by Platform Builder boots with black screen" Short: 1. Start Platform Builder with your composed Platform 2. Select "Platform" on the menu bar. 3. Now click subitem "Settings" 4. Select the "Build Options" tab 5. Uncheck "Enable KITL (no IMGNOKITL=1)"
{ "language": "en", "url": "https://stackoverflow.com/questions/7508586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing if a string contains one of several thousand substrings I'm going to be running through live twitter data and attempting to pull out tweets that mention, for example, movie titles. Assuming I have a list of ~7000 hard-coded movie titles I'd like to look against, what's the best way to select the relevant tweets? This project is in it's infancy so I'm open to any looking into any solution (i.e. language agnostic.) Any help would be greatly appreciated. Update: I'd be curious if anyone had any insight to how the Yahoo! Placemaker API, solves this problem. It can take a text string and return a geocoded JSON result of all the locations mentioned in it. A: You could try Wu and Manber's A Fast Algorithm For Multi-Pattern Searching. The multi-pattern matching problem lies at the heart of virus scanning, so you might look to scanner implementations for inspiration. ClamAV, for example, is open source and some papers have been published describing its algorithms: Lin, Lin and Lai: A Hybrid Algorithm of Backward Hashing and Automaton Tracking for Virus Scanning (a variant of Wu-Manber; the paper is behind the IEEE paywall). Cha, Moraru, et al: SplitScreen: Enabling Efficient, Distributed Malware Detection A: If you use compiled regular expressions, it should be pretty fast. Maybe especially if you put lots of titles in one expression. A: Efficiently searching for many terms in a long character sequence would require a specialized algorithm to avoid testing for every term at every position. But since it sounds like you have short strings with a known pattern, you should be able to use something fairly simple. Store the set of titles you care about in a hash table or tree. Parse out "string1" and "string2" from each tweet using a regex, and test whether they are contained in the set. A: Working off what erickson suggested, the most feasible search is for the ("is better than" in your example), then checking for one of the 7,000 terms. You could instead narrow the set by creating 7,000 searches for "[movie] is better than" and then filtering manually on the second movie, but you'll probably hit the search rate limit pretty quickly. You could speed up the searching by using a dedicated search service like Solr instead of using text parsing. You might be able to pull out titles quickly using some natural language processing service (OpenCalais?), but that would be better suited to batch processing. A: For simultaneously searching for a large number of possible targets, the Rabin-Karp algorithm can often be useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Renaming Files with Excel VBA Here's what I need to do. I have these two columns in an excel sheet. With file names. First column has the current filename and the second column has the names I want the files to be renamed to. I need to use this as there's no pattern in renaming. For example, the below may be a set of files ... Current Name > Rename To --------------------------- Abc.jpg > Dinner.jpg Xyz.jpg > Driving.jpg 123.jpg > Sunset.jpg I know it should be easy to do this in VBA, but not exactly sure how. Any help would be much appreciated. A: I think you could do something like this, using the Name function to rename the files, however, you will probably need to make sure the 2 columns have the complete file path, i.e. "C:\Temp\ABC.jpg" Dim Source As Range Dim OldFile As String Dim NewFile As String Set Source = Cells(1, 1).CurrentRegion For Row = 1 To Source.Rows.Count OldFile = ActiveSheet.Cells(Row, 1) NewFile = ActiveSheet.Cells(Row, 2) ' rename files Name OldFile As Newfile Next
{ "language": "en", "url": "https://stackoverflow.com/questions/7508605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: PHP form design help Possible Duplicate: Robust, Mature HTML Parser for PHP Help coding an HTML Form This is a mockup of design that I have in mind - http://i.imgur.com/ujiLb.jpg From each set of options, only 1 must be checked and depending on the combination of checked boxes the 'submit' button directs to a webpage. The two features will be Price(Please choose one) 1-99 100-249 250-499 Manufacturer(Please choose one) A B C [SUBMIT BUTTON] The coding that I can understand which is definitely wrong is: //search page ... <form action='search.php' method='post'> <input type=radio name=product value='a'>A?</input> <input type=radio name=product value='b'>B?</input> <input type=radio name=product value='c'>C?</input> <br> <input type=radio name=price value='5'>5-10?</input> <input type=radio name=price value='10'>11-15?</input> <input type=radio name=price value='other'>15+?</input> ... </form> And in search.php, something like ... <?php $product = $_POST("product"); $price = $_POST("price"); ... if (($product == "A") && ($price == "5")) { Location("a-5-10.html"); // Products matching A, price 5-10 etc elseif (($product == "B") && ($price == "5")) { Location("b-5-10.html"); //Products matching b, price 5-10 etc .... endif ?> EDIT as per OP's comments, the request is not being redirected to "b-5-10.html" or "a-5-10.html" etc. A: $_POST is an array, not a function, you want $_POST['product']; $product = $_POST["product"]; //note [ and ] instead of ( and ) $price = $_POST["price"]; Also Location is not a function that I am aware of as @erisco pointed out you need to use header if (($product == "A") && ($price == "5")) { header("Location: a-5-10.html"); // Products matching A, price 5-10 etc } //also note the closing brace elseif (($product == "B") && ($price == "5")) { header("Location: b-5-10.html"); //Products matching b, price 5-10 etc } //again, closing brace, not "endif"
{ "language": "en", "url": "https://stackoverflow.com/questions/7508609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't Flowdocument's tooltip show? I have a very strange problem with tooltips inside FlowDocument. Finally I am able to narrow it down to the following xaml. Paste the following xaml into kaxaml or Blend, you will see the problem. <FlowDocumentScrollViewer> <FlowDocument Background="Transparent"> <Table> <Table.Columns> <TableColumn Width="15" /> <TableColumn /> </Table.Columns> <TableRowGroup> <TableRow> <TableCell> <Paragraph Margin="0,3.10333333333333,0,0"> <Run FontSize="5">●</Run> </Paragraph> </TableCell> <TableCell> <Paragraph> <Run FontSize="13" ToolTip="This is a tooltip">I have a tooltip</Run> </Paragraph> <Paragraph LineHeight="0.1" Background="Transparent"> <Figure Name="MyFigure" HorizontalAnchor="ColumnLeft" VerticalAnchor="ParagraphTop" CanDelayPlacement="False" Width="200" Padding="0,0,0,0"> <BlockUIContainer> <Grid> <Rectangle Name="MyRectangle" Fill="Green" Width="Auto" Height="50" /> </Grid> </BlockUIContainer> </Figure> </Paragraph> </TableCell> </TableRow> </TableRowGroup> </Table> </FlowDocument> </FlowDocumentScrollViewer> The tooltip doesn't open. However if I do one of the following, the tooltip will show. * *Change MyFigure's Width to 15 *Change MyRectangle's Height to 5 It almost feels like the Run is covered by something so its tooltip doesn't show. A: Try to set IsDocumentEnabled="True" on FlowDocument. Edit: IsDocumentEnabled property is on the RichTextBox and won't help in this case to make tooltip work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: DataGridView.Rows.RemoveAt(int index) doesn't remove row in windows form? int i = dataGridView1.CurrentRow.Index; dataGridView1.Rows.RemoveAt(i); The above code for deleting current selected row (only allow to select 1 row) but I still can see the row remains in datagridview. Did I miss an update or invalidate ? ps: dataGridView1 is data-bound. ps2: I use linq query to bind data and I don't want to query again for just to show a row was deleted, I think it will slow down performance. A: I think the solution depends on how you bind the data. If you are binding a BindingList, RemoveAt() method removes handles everything for you and you don't have to refresh the DataGridView. Try below and see... dataGridView1.Refresh(); OR re-bind the data and see.. dataGridView1.DataSource = myDataSource; dataGridView1.Refresh(); A: remove the item from the datasource, and bind again. since the data comes from linq, before binding, you can do: var result = fooLinq.ToList(); dataGridView1.DataSource = result; //to remove and bind again var result = dataGridView1.DataSource as List<FooType>; result.RemoveAt(fooIndex); dataGridView1.DataSource = result; A: If I understand you correctly, you want to delete rows selected by a user from your DGV. * *Use the DataGridViewRowCollection of your DGV rather than the DataRowCollection of the DataTable. The DataGridViewRow has the Selected property that indicates whether a row is selected or otherwise. *Once you have determined that a row is to be deleted, you can use the Remove method of the DataGridViewRowCollection to delete the item from the grid, e.g. YerDataGridView.Rows.Remove(row) *Note that at this point, although the item is removed from the DGV, it still has not been deleted from the Access DB. You need to call the TableAdapter Update method on your DataSet/DataTable to commit the deletions to the DB, e.g. YerTableAdapter.Update(YerDataSet) I normally would call Update once to commit the changes only after having removed all the items to be deleted from the DGV.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can i change my "read more" to an image with hover effect? I'm currently editing my premade layout downloaded in the internet and i would like to edit the "Read More" link to an image. The best example that i want to achieve is like in the website of www.hongkiat.com. When you hover Continue Reading, the background changes. my code in the template is this: <div class="entry"> <p><?php the_content('Read More...'); ?></p> </div><!--entry--> Thank you very much in advance! A: You can add an HTML <img> tag as a parameter: <?php the_content('Read more...<img src="' . get_bloginfo('template_directory'). '/images/leaf.gif" alt="read more" title="Read more..." />'); ?> A: Assuming you have <div class="entry"> <p><?php the_content('<span class="readmore">Read More...</span>'); ?></p> </div><!--entry--> You can add a behavior in CSS like so: span.readmore{background-color:red}
{ "language": "en", "url": "https://stackoverflow.com/questions/7508625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FMod Memory Stream Problem EDIT: Well...that's very interesting. I made settings into a pointer and passed that. Worked beautifully. So, this is solved. I'll leave it open for anyone curious to the answer. I'm having an issue creating a sound in FMod from a memory stream. I looked at the loadfrommemory example shipped with FMod and followed that. First, the code I'm using... CSFX::CSFX(CFileData *fileData) { FMOD_RESULT result; FMOD_CREATESOUNDEXINFO settings; settings.cbsize = sizeof(FMOD_CREATESOUNDEXINFO); settings.length = fileData->getSize(); _Sound = 0; std::string temp = ""; for (int i = 0; i < fileData->getSize(); i++) temp += fileData->getData()[i]; result = tempSys->createSound(temp.c_str(), FMOD_SOFTWARE | FMOD_OPENMEMORY, &settings, &_Sound); } As it is like this, I get an access violation on tempSys->createSound(). I've confirmed that tempSys is valid as it works when creating sounds from a file. I've also confirmed the char * with my data is valid by writing the contents to a file, which I was then able to open in Media Player. I have a feeling there's a problem with settings. If I change that parameter to 0, the program doesn't blow up and I end up with result = FMOD_ERR_INVALID_HANDLE (which makes sense considering the 3rd parameter is 0). Any idea what I'm doing wrong? Also, please disregard the use of std::string, I was using it for some testing purposes. A: Solved by turning settings into a pointer. See code below: CSFX::CSFX(CFileData *fileData) { FMOD_RESULT result; FMOD_CREATESOUNDEXINFO * settings; _Sound = 0; std::string temp = ""; for (int i = 0; i < fileData->getSize(); i++) temp += fileData->getData()[i]; settings = new FMOD_CREATESOUNDEXINFO(); settings->cbsize = sizeof(FMOD_CREATESOUNDEXINFO); settings->length = fileData->getSize(); result = tempSys->createSound(temp.c_str(), FMOD_SOFTWARE | FMOD_OPENMEMORY, settings, &_Sound); delete settings; settings = 0; } A: You need to memset settings before using it. memset(&settings, 0, sizeof(FMOD_CREATESOUNDEXINFO); Otherwise it will contain garbage and potentially crash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is there a way to build persistence in soapui or any similar software? yeah so, our application would be connecting to not yet existing services. We were given WSDLs for those services and we mocked them in soapiu. Is there a way to build rudimentary persistence in soapui or any similar software so that we could have some functionality without actually building the service ourselves? I've researched on datasinks and datasources for soapui but it seems it only works for testsuites. A: You build your mockservice, and use enough scripting and datagens to make it seem like the real deal. Leave it running on someone's PC, or let each developer or team have their own instance to hit. Then you just send your requests, and SoapUI returns the response. In some cases, a canned response is good enough. In other cases, you may need to pick a response based on something in the request. For example, suppose my StockQuote service has two responses - a good one with the stock price, and a failure, with "symbol not found". It's simple to script the mockservice so that it gives a known price for symbol 'AA', makes up a price for 'BB', and returns the "unknown symbol" response for everything else. Here is the tutorial: http://www.soapui.org/Service-Mocking/creating-dynamic-mockservices.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7508628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does printf not work before infinite loop? I am trying to make a small program that includes an infinite loop to wait for signal input from the user. I wanted to print out a message about the current working directory before beginning the infinite loop. The message works on its own, but when I put the infinite loop into the code the message does not print out (but the terminal does loop infinitely). The code is: #include <stdio.h> int MAX_PATH_LENGTH = 100; main () { char path[MAX_PATH_LENGTH]; getcwd(path, MAX_PATH_LENGTH); printf("%s> ", path); while(1) { } } If I take out while(1) { } I get the output: ad@ubuntu:~/Documents$ ./a.out /home/ad/Documents> Why is this? Thank you! A: When you call printf, the output doesn't get printed immediately; instead, it goes into a buffer somewhere behind the scenes. In order to actually get it to show up on the screen, you have to call fflush or something equivalent to flush the stream. This is done automatically for you whenever you print a newline character* and when the program terminates; it's that second case that causes the string to show up when you remove the infinite loop. But with the loop there, the program never ends, so the output never gets flushed to the screen, and you don't see anything. *As I just discovered from reading the question itsmatt linked in a comment, the flush-on-newline only happens when the program is printing to a terminal, and not necessarily when it's printing to a file. A: Because you don't have a new-line character at the end of your string. stdout is line-buffered by default, which means it won't flush to console until it encounters a new-line character ('\n'), or until you explicitly flush it with fflush(). A: Perhaps the output is not getting flushed. Try: printf("%s> ", path); fflush(stdout); A: Because the stdout hasn't been flushed. Call fflush(stdout); before your loop. A: Because the output is not flushed. Add fflush(stdout); before the while loop will solve the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to multiply a scalar throughout a specific column within a NumPy array? I need to do some analysis on a large dataset from a hydrolgeology field work. I am using NumPy. I want to know how I can: * *multiply e.g. the 2nd column of my array by a number (e.g. 5.2). And then *calculate the cumulative sum of the numbers in that column. As I mentioned I only want to work on a specific column and not the whole array. A: Sure: import numpy as np # Let a be some 2d array; here we just use dummy data # to illustrate the method a = np.ones((10,5)) # Multiply just the 2nd column by 5.2 in-place a[:,1] *= 5.2 # Now get the cumulative sum of just that column csum = np.cumsum(a[:,1]) If you don't want to do this in-place you would need a slightly different strategy: b = 5.2*a[:,1] csum = np.cumsum(b) A: you can do this in two simple steps using NumPy: >>> # multiply column 2 of the 2D array, A, by 5.2 >>> A[:,1] *= 5.2 >>> # assuming by 'cumulative sum' you meant the 'reduced' sum: >>> A[:,1].sum() >>> # if in fact you want the cumulative sum (ie, returns a new column) >>> # then do this for the second step instead: >>> NP.cumsum(A[:,1]) with some mocked data: >>> A = NP.random.rand(8, 5) >>> A array([[ 0.893, 0.824, 0.438, 0.284, 0.892], [ 0.534, 0.11 , 0.409, 0.555, 0.96 ], [ 0.671, 0.817, 0.636, 0.522, 0.867], [ 0.752, 0.688, 0.142, 0.793, 0.716], [ 0.276, 0.818, 0.904, 0.767, 0.443], [ 0.57 , 0.159, 0.144, 0.439, 0.747], [ 0.705, 0.793, 0.575, 0.507, 0.956], [ 0.322, 0.713, 0.963, 0.037, 0.509]]) >>> A[:,1] *= 5.2 >>> A array([[ 0.893, 4.287, 0.438, 0.284, 0.892], [ 0.534, 0.571, 0.409, 0.555, 0.96 ], [ 0.671, 4.25 , 0.636, 0.522, 0.867], [ 0.752, 3.576, 0.142, 0.793, 0.716], [ 0.276, 4.255, 0.904, 0.767, 0.443], [ 0.57 , 0.827, 0.144, 0.439, 0.747], [ 0.705, 4.122, 0.575, 0.507, 0.956], [ 0.322, 3.71 , 0.963, 0.037, 0.509]]) >>> A[:,1].sum() 25.596156138451427 just a few simple rules are required to grok element selection (indexing) in NumPy: * *NumPy, like Python, is 0-based, so eg, the "1" below refers to the second column *commas separate the dimensions inside the brackets, so [rows, columns], eg, A[2,3] means the item ("cell") at row three, column four *a colon means all of the elements along that dimension, eg, A[:,1] creates a view of A's column 2; A[3,:] refers to the fourth row A: To multiply a constant with a specific column or row: import numpy as np; X=np.ones(shape=(10,10),dtype=np.float64); X; ### this is our default matrix array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]) ## now say we want to multiple it with 10 X=X*10; array([[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]]) ### Now if, we want to mulitply 3,5, 7 column with 5 X[:,[3,5,7]]=X[:,[3,5,7]]*5 array([[10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.], [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.]]) Similarly, we can do it for any columns. Hope it clarifies.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Hyperlinks A HREF do not work I'm a bit fooling around with a new website idea. But when i was testing it the A HREF does not work. It's not even showing a finger/hand pointer. It's the text at the content area (the first white block under the header, but not the menu). The headers should be links to the posts (Wordpress). screenshot of the links that do not work (red arrows): http://new.go80.nl/screenshots/brokenlinksscreen.png Actually all the links in that area do not work. And at the Contact page not even the google maps work. I can't move around and can't click the links. Can somebody please help me figure this out? I don't want to start over. Website: http://new.go80.nl/headlines EDIT, i first linked to the home page. Beacouse I'm new here i could only add one link and the home page actually is OK so I linked to the Headlines page. Thank you guys very much! Greetings, Joeri Kosters A: It looks like focus is going to the pagewrap div by default EDIT #2: Make sure you give an example that actually shows the problem : ) It looks like somehow you've gotten z-index: -1 on div#content, so it is falling 'behind' div#pagewrap and so is not clickable. Get rid of that and you should be fine. A: Umm, you haven't put this text inside <a></a> elements, according to the HTML source. A: There is a z-index: -1 in your global.css in your #content id section. Remove this and your problem is fixed. The z-index is making all of the #content links unreachable by the mouse. A: Umm just put those headlines text in between the "a" and href tags. <a href="http://yourlink/link.htm">Your Heading</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7508641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PyGTK Spacing in an HBox I'm new to GTK, I'm trying to figure out how to accomplish something like this: +---+------+---+ | | | | | | | | | | | | | | | | | | | | | | | | +---+------+---+ I want this done in an HBox. How would I accomplish this? Thanks. A: It is done with "packing". I always keep the class reference under my pillow : http://www.pygtk.org/docs/pygtk/gtk-class-reference.html Samples in the good tutorial found here : http://www.pygtk.org/pygtk2tutorial/sec-DetailsOfBoxes.html And finally, this shows up something like your drawing : import gtk as g win = g.Window () win.set_default_size(600, 400) win.set_position(g.WIN_POS_CENTER) win.connect ('delete_event', g.main_quit) hBox = g.HBox() win.add (hBox) f1 = g.Frame() f2 = g.Frame() f3 = g.Frame() hBox.pack_start(f1) hBox.pack_start(f2) hBox.pack_start(f3) win.show_all () g.main () Have fun ! (and I hope my answer is helpful) A: The answer is pack_start() and pack_end() The function has a few parameters you can send to it that give you the desired effect If you use Louis' example: hBox.pack_start(f1, expand =False, fill=False) hBox.pack_start( f2, expand=True, fill=True, padding=50) hBox.pack_end(f3, expand=False, fill=False) Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7508651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: where is $content variable declared in Yii? I am using Yii Framework. In the view, main.php, there is a reference to the $content block <?php echo $content; ?> I could not find it anywhere in the model or elsewhere in the demo project. Can someone shed light on this? Or may be this variable is never declared? I have not modified the demo project yet. A: The $content value in layout files contains the rendered content of the template specified as the first attribute of the render command. (It's automatically created so I wouldn't use "content" as an additional variable name or it could cause confusion.) The variables that you pass as an additional array argument in the render statement are made available to the template you are calling, not to the layout. If you have nested layouts, the value of $content cascades from parent to child. A: All your controllers are derived from CController class. CController has a function named render which you call it for rendering your views. It works like this: * *beforeRender is called. *renderPartial is called on your view file, and its output is stored in $output. *renderFile is called on the layout file, with a parameter named content like this: $this->render(layoutFile, array('content'=>$output)); So the $content is coming from here. You can see the actual code here: Source code, and documentation here: Documentation A: Found answer from Yii Documentation / Layouts, For example, a layout may contain a header and a footer, and embed the view in between, like this: ......header here...... <?php echo $content; ?> ......footer here...... where $content stores the rendering result of the view. It is indeed all the text in one of the view (in my case index.php). $content basically takes the content of view. It is not declared anywhere and it is be default. As the answer said, you should not use declare/use $content in your code. A: I think its being set from the controller which is calling this view. In the controller look for something like the following $this->render('main', array('content'=>"something here"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7508655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Turn accordion widget on and off I am setting up different CSS for the basic three media Screen, tablet and smartphone. I have a two list I would like to leave as is for Screen but would like to have the two lists become an accordion widget in Tablet mode. My idea was to go ahead and put everything into the widget. The size that I have set for Tablet view would turn on the jquery script and the Desktop view would turn the script off and the content would just show in normal looking 's So if the SpryAccordion.js file looks like this: (I have some actionscript exp. So I understand if/else statements but don't know how to use them in js) (function() { // BeginSpryComponent if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Widget) Spry.Widget = {}; Spry.Widget.Accordion = function(element, opts) { //all the spry code...// }; })(); how would I wrap this to turn the widget on and off? Or is there a better way to do this? I'm very new to jquery. My other option is to have duplicate content in a Div and the widget and turn the visibility each on/off with css. But that just wouldn't be very elegant. Please help. A: I think I understand your question. So basically you want to be able to turn the accordion on and off correct? One way of doing it is simply define the the Spry.Widget.Accordion inside of its own function and only call it when you want to activate the accordion. Is that kind of what you were looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7508660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change text in UILabel with NSMutablearray data I'm trying to change the text of a UILabel with text from an array upon a button click, but it doesn't do anything. @interface Test01AppDelegate : NSObject <UIApplicationDelegate> { UILabel *helloLabel; UIButton *hellobutton; NSMutableArray *madWords; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UIButton *hellowButton; @property (nonatomic, retain) IBOutlet UILabel *hellowLabel; @property (nonatomic, retain) NSMutableArray *madWords; - (void) madArrays; - (IBAction)helloYall; @end and #import "Test01AppDelegate.h" @implementation Test01AppDelegate @synthesize window = _window; @synthesize hellowButton; @synthesize hellowLabel; @synthesize madWords; - (void) madArrays { [madWords addObject:@"Part A"]; [madWords addObject:@"Part B"]; [madWords addObject:@"Part C"]; [madWords addObject:@"Part D"]; } - (IBAction)helloYall { [self madArrays]; self.hellowLabel.text = [madWords objectAtIndex:0]; } I can set the helloLabel text with @"some text here"; and it works fine. Also, I tried copying the "madArrays" method into the "helloYall" method and it still didn't work. As I said, I can manually set the text and it works, but I'd like to pull the info from an array. Eventually, I'd like to loop through the array to grab the text on each button press, but one step at a time. Thanks. A: You never create the madWords array. You need to add: self.madWords = [NSMutableArray array]; at the top of: - (void) madArrays { would probably be a good place. Other possibly good places would be i the class init method or the view controller viewWillAppear method. A: // Or you can try this in your init Method: //first allocate the ivar - (void)myInitMethod { madArrays = [[NSMutableArray]alloc]init]; } //then you can do anything directly to the ivar or throughout de setter - (void)doAnythingWithiVar { // do your stuff } //when you are done you can dealloc your ivar - (void)dealloc { [madArrays release]; [super dealloc]; } A: It looks like madArrays is still nil when you come to populate it. At some point you need something like [self setMadArrays:[[NSMutableArray alloc] init]];. Also, don't forget to release madArrays in the dealloc before calling super as you'll have a memory leak.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does IEnumerable always imply a collection? Just a quick question regarding IEnumerable: Does IEnumerable always imply a collection? Or is it legitimate/viable/okay/whatever to use on a single object? A: The IEnumerable and IEnumerable<T> interfaces suggest a sequence of some kind, but that sequence doesn't need to be a concrete collection. For example, where's the underlying concrete collection in this case? foreach (int i in new EndlessRandomSequence().Take(5)) { Console.WriteLine(i); } // ... public class EndlessRandomSequence : IEnumerable<int> { public IEnumerator<int> GetEnumerator() { var rng = new Random(); while (true) yield return rng.Next(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } A: Yes, IEnumerable implies a collection, or possible collection, of items. The name is derived from enumerate, which means to: * *Mention (a number of things) one by one. *Establish the number of. A: It is always and mandatory that IEnumerable is used on a single object - the single object is always the holder or producer of zero or more other objects that do not necessarily have any relation to IEnumerable. It's usual, but not mandatory, that IEnumerable represents a collection. Enumerables can be collections, as well as generators, queries, and even computations. Generator: IEnumerable<int> Generate( int initial, Func<int, bool> condition, Func<int, int> iterator) { var i = initial; while (true) { yield return i; i = iterator(i); if (!condition(i)) { yield break; } } } Query: IEnumerable<Process> GetProcessesWhereNameContains(string text) { // Could be web-service or database call too var processes = System.Diagnostics.Process.GetProcesses(); foreach (var process in processes) { if (process.ProcessName.Contains(text)) { yield return process; } } } Computation: IEnumerable<double> Average(IEnumerable<double> values) { var sum = 0.0; var count = 0; foreach (var value in values) { sum += value; yield return sum/++count; } } LINQ is itself a series of operators that produce objects that implement IEnumerable<T> that don't have any underlying collections. Good question, BTW! NB: Any reference to IEnumerable also applies to IEnumerable<T> as the latter inherits the former. A: According to the docs, it exposes the enumerator over a collection. A: You can certainly use it on a single object, but this object will then just be exposed as an enumeration containing a single object, i.e. you could have an IEnumerable<int> with a single integer: IEnumerable<int> items = new[] { 42 }; A: IEnumerable represents a collection that can be enumerated, not a single item. Look at MSDN; the interface exposes GetEnumerator(), which ...[r]eturns an enumerator that iterates through a collection. A: Yes, IEnumerable always implies a collection, that is what enumerate means. What is your use case for a single object? I don't see a problem with using it on a single object, but why do want to do this? A: I'm not sure whether you mean a "collection" or a .NET "ICollection" but since other people have only mentioned the former I will mention the latter. http://msdn.microsoft.com/en-us/library/92t2ye13.aspx By that definition, All ICollections are IEnumerable. But not the other way around. But most data structure (Array even) just implement both interfaces. Going on this train of thought: you could have a car depot (a single object) that does not expose an internal data structure, and put IEnumerable on it. I suppose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7508663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }