text
stringlengths
8
267k
meta
dict
Q: Date format from 26.09.2011 to 26.9.2011 Possible Duplicate: Remove leading zeros from abbreviated date with PHP I have a problem formating date from 26.09.2011 to 26.9.2011. Of course if there is two digits month there should be two digits (26.12.2011). I am looking for answer all over web. Could anyone tell me how to acomplish that. Thanks for answer. A: http://php.net/manual/en/function.date.php echo date("j.n.Y"); will print current date in the format you specified. A: $date = new DateTime('26.09.2011'); echo $date->format('d.n.Y'); m prints two digits month, n prints month without leading zeros.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: jQuery Drop event is not working I facing a weird problem here. I already have a simple try-out for jquery drag-n-drop and it WORKS. However, now i wan to move the code from the try-out project to the project file i working right now. Everything is the SAME, but i just cant get the drop event to be fired. It is really urgent, please help... I included my code, just in case... $('.image').draggable({ cursor: 'move' }); // Put img resizable is to have the ghost $('.image img').resizable({ ghost: true, stop: function (event, ui) { var eid = $(this).parent().attr('id'); alert(eid); var wid = $(this).width(); alert(wid); var hei = $(this).height(); alert(hei); updateSize(eid, wid, hei); } }); // Variable to hold drop options var options = {}; // Once image re-drop, update its position options.drop = function (event, ui) { // Check image id to check whether image exist or not if (ui.draggable.attr('id').match(/_(\d+)$/) != null) { var element = ui.draggable; updatePosition(element); } else { // Store the clone position var leftPosition = ui.offset.left; var topPosition = ui.offset.top; alert('Left: ' + leftPosition + ' Top: ' + topPosition); // Variable to generate new image id var counter = new Date().valueOf(); // Create the clone //var element = ui.draggable.clone(); // Assign new id for clone element var oldID = ui.draggable.attr('id'); alert('old id ' + oldID); ui.draggable.attr('id', (oldID + '_' + counter)); // Call CreateContainer createContainer(ui.draggable, oldID, topPosition, leftPosition); } }; $('#rightframe').droppable(options); A: It seems like it works fine: http://jsfiddle.net/DrUKa/
{ "language": "en", "url": "https://stackoverflow.com/questions/7537368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to include a PHP variable inside a MySQL statement I'm trying to insert values in the contents table. It works fine if I do not have a PHP variable inside VALUES. When I put the variable $type inside VALUES then this doesn't work. What am I doing wrong? $type = 'testing'; mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')"); A: The best option is prepared statements. Messing around with quotes and escapes is harder work to begin with, and difficult to maintain. Sooner or later you will end up accidentally forgetting to quote something or end up escaping the same string twice, or mess up something like that. Might be years before you find those type of bugs. http://php.net/manual/en/pdo.prepared-statements.php A: The rules of adding a PHP variable inside of any MySQL statement are plain and simple: 1. Use prepared statements This rule covers 99% of queries and your query in particular. Any variable that represents an SQL data literal, (or, to put it simply - an SQL string, or a number) MUST be added through a prepared statement. No exceptions. This approach involves four basic steps * *in your SQL statement, replace all variables with placeholders *prepare the resulting query *bind variables to placeholders *execute the query And here is how to do it with all popular PHP database drivers: Adding data literals using mysqli $type = 'testing'; $reporter = "John O'Hara"; $query = "INSERT INTO contents (type, reporter, description) VALUES(?, ?, 'whatever')"; $stmt = $mysqli->prepare($query); $stmt->bind_param("ss", $type, $reporter); $stmt->execute(); The code is a bit complicated but the detailed explanation of all these operators can be found in my article, How to run an INSERT query using Mysqli, as well as a solution that eases the process dramatically. For a SELECT query you will need to add just a call to get_result() method to get a familiar mysqli_result from which you can fetch the data the usual way: $reporter = "John O'Hara"; $stmt = $mysqli->prepare("SELECT * FROM users WHERE name=?"); $stmt->bind_param("s", $reporter); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc(); // or while (...) Adding data literals using PDO $type = 'testing'; $reporter = "John O'Hara"; $query = "INSERT INTO contents (type, reporter, description) VALUES(?, ?, 'whatever')"; $stmt = $pdo->prepare($query); $stmt->execute([$type, $reporter]); In PDO, we can have the bind and execute parts combined, which is very convenient. PDO also supports named placeholders which some find extremely convenient. 2. Use white list filtering Any other query part, such as SQL keyword, table or a field name, or operator - must be filtered through a white list. Sometimes we have to add a variable that represents another part of a query, such as a keyword or an identifier (a database, table or a field name). It's a rare case but it's better to be prepared. In this case, your variable must be checked against a list of values explicitly written in your script. This is explained in my other article, Adding a field name in the ORDER BY clause based on the user's choice: Unfortunately, PDO has no placeholder for identifiers (table and field names), therefore a developer must filter them out manually. Such a filter is often called a "white list" (where we only list allowed values) as opposed to a "black-list" where we list disallowed values. So we have to explicitly list all possible variants in the PHP code and then choose from them. Here is an example: $orderby = $_GET['orderby'] ?: "name"; // set the default value $allowed = ["name","price","qty"]; // the white list of allowed field names $key = array_search($orderby, $allowed, true); // see if we have such a name if ($key === false) { throw new InvalidArgumentException("Invalid field name"); } Exactly the same approach should be used for the direction, $direction = $_GET['direction'] ?: "ASC"; $allowed = ["ASC","DESC"]; $key = array_search($direction, $allowed, true); if ($key === false) { throw new InvalidArgumentException("Invalid ORDER BY direction"); } After such a code, both $direction and $orderby variables can be safely put in the SQL query, as they are either equal to one of the allowed variants or there will be an error thrown. The last thing to mention about identifiers, they must be also formatted according to the particular database syntax. For MySQL it should be backtick characters around the identifier. So the final query string for our order by example would be $query = "SELECT * FROM `table` ORDER BY `$orderby` $direction"; A: To avoid SQL injection the insert statement with be $type = 'testing'; $name = 'john'; $description = 'whatever'; $con = new mysqli($user, $pass, $db); $stmt = $con->prepare("INSERT INTO contents (type, reporter, description) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $type , $name, $description); $stmt->execute(); A: The text inside $type is substituted directly into the insert string, therefore MySQL gets this: ... VALUES(testing, 'john', 'whatever') Notice that there are no quotes around testing, you need to put these in like so: $type = 'testing'; mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')"); I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used: * *MySQL - SQL Injection Prevention A: That's the easy answer: $query="SELECT * FROM CountryInfo WHERE Name = '".$name."'"; and you define $name whatever you want. And another way, the complex way, is like that: $query = " SELECT '" . $GLOBALS['Name'] . "' .* " . " FROM CountryInfo " . " INNER JOIN District " . " ON District.CountryInfoId = CountryInfo.CountryInfoId " . " INNER JOIN City " . " ON City.DistrictId = District.DistrictId " . " INNER JOIN '" . $GLOBALS['Name'] . "' " . " ON '" . $GLOBALS['Name'] . "'.CityId = City.CityId " . " WHERE CountryInfo.Name = '" . $GLOBALS['CountryName'] . "'";
{ "language": "en", "url": "https://stackoverflow.com/questions/7537377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "77" }
Q: How to compare time to a time range specified in Prolog? Let's say i have a structure comparetime(hours,mins), when a user keys example comparetime(10,40) , the structure will make comparison on a time range specified example timing entered 1) from 10:00 to 12:00 will print a message and 2) from 18:00 to 20:00 will print a message . if the time keyed is not inside the range, it will also print a message. how can I do this ? it's easy to compare words but i'm really having a tough time with comparing time. A: It's easy compare words? You should try it when internationalization is involved to appreciate how difficult could be! Far easier is compare pair of integers, as from your problem (if I understand the question). message_on_range(1, 10:00, 12:00, 'it\'s morning!'). message_on_range(2, 18:00, 20:00, 'it\'s evening!'). comparetime(Hours, Mins) :- message_on_range(_, Start, Stop, Message), less_equal_time(Start, Hours:Mins), less_equal_time(Hours:Mins, Stop), write(Message), nl. comparetime(_Hours, _Mins) :- write('please check your clock!'), nl. less_equal_time(H1:S1, H2:S2) :- H1 == H2 -> S1 =< S2 ; H1 < H2. You should be aware of Prolog features: your problem could require a cut after the message has been printed! I.e. ... less_equal_time(Hours:Mins, Stop), write(Message), nl, !.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Count data from multiple tables using SUM I have table with positions tbl_positions id position 1 Driver 2 Lobby 3 Support 4 Constructor and in other table i have users EDIT: tbl_workers id name position position2 status 1 John 2 3 4 2 Mike 3 2 2 3 Kate 2 0 3 4 Andy 1 0 0 i do request of positions SELECT p.id, p.position, SUM(CASE w.Status WHEN 2 THEN 1 ELSE 0 END) AS booked, SUM(CASE w.Status WHEN 3 THEN 1 ELSE 0 END) AS placed FROM tbl_positions AS p LEFT JOIN tbl_workers AS w ON w.position=p.id GROUP BY p.id, p.position I need output like this in single query. Position booked placed Driver 0 0 Lobby 1 2 Support 0 2 Constructor 0 0 I need to evalate both field positon1 and position2 instead of one. I think its easy to modify it but i cannot find the right solution please help. EDIT : Added status 4 A: Instead of joining to tbl_workers you could join to its unpivoted variation where position and position2 would be in the same column but in different rows. Here's how the unpivoting might look like: SELECT w.id, w.name, CASE x.pos WHEN 1 THEN w.position ELSE w.position2 END AS position, w.status FROM tbl_workers AS w CROSS JOIN (SELECT 1 AS pos UNION ALL SELECT 2) AS x Here's the entire query, which is basically your original query with the above query substituting for the tbl_workers table: SELECT p.id, p.position, SUM(CASE w.Status WHEN 2 THEN 1 ELSE 0 END) AS booked, SUM(CASE w.Status WHEN 3 THEN 1 ELSE 0 END) AS placed FROM tbl_positions AS p LEFT JOIN ( SELECT w.id, w.name, CASE x.pos WHEN 1 THEN w.position ELSE w.position2 END AS position, w.status FROM tbl_workers AS w CROSS JOIN (SELECT 1 AS pos UNION ALL SELECT 2) AS x ) AS w ON w.position=p.id GROUP BY p.id, p.position UPDATE This is a modified script according to additional request in comments: SELECT p.id, p.position, SUM(CASE w.Status WHEN 2 THEN 1 ELSE 0 END) AS booked, SUM(CASE w.Status WHEN 3 THEN 1 ELSE 0 END) AS placed FROM tbl_positions AS p LEFT JOIN ( SELECT w.id, w.name, CASE x.pos WHEN 1 THEN w.position ELSE w.position2 END AS position, CASE w.status WHEN 4 THEN CASE x.pos WHEN 1 THEN 3 ELSE 2 END ELSE w.status END AS status FROM tbl_workers AS w CROSS JOIN (SELECT 1 AS pos UNION ALL SELECT 2) AS x ) AS w ON w.position=p.id GROUP BY p.id, p.position The idea is to substitute the 4 status in the subselect with 3 or 2 depending on whether we are currently to pull position or position2 as the unified position. The outer select keeps using the same logic as before. A: not really sure what you mean by "evaluate both fields" - but here is an example on how to sum up both: SELECT P.ID, P.POSITION, ((SELECT SUM (CASE W.STATUS WHEN 2 THEN 1 ELSE 0 END) FROM TBL_WORKERS W WHERE W.POSITION = P.ID) + (SELECT SUM (CASE W.STATUS WHEN 2 THEN 1 ELSE 0 END) FROM TBL_WORKERS W WHERE W.POSITION2 = P.ID)) AS BOOKED, ((SELECT SUM (CASE W.STATUS WHEN 3 THEN 1 ELSE 0 END) FROM TBL_WORKERS W WHERE W.POSITION = P.ID) + (SELECT SUM (CASE W.STATUS WHEN 3 THEN 1 ELSE 0 END) FROM TBL_WORKERS W WHERE W.POSITION2 = P.ID)) AS PLACED FROM TBL_POSITIONS P A: since your data is not normalized (ie: two columns both representing a position in a single row), I would do a UNION of the workers first, then apply your outer count/group by... something like... Each part of the inner query is pre-aggregating and only counting for the records qualifying the status 2 or 3 and have a position. So, if you have a large table, it would be more noticeable for performance. Then, that result gets summed at the outer level for all possible positions using COALESCE() to prevent NULL values in your output result. SELECT p.id, p.position, coalesce( SUM(w.Booked), 0 ) AS booked, coalesce( SUM(w.Placed), 0 ) AS placed FROM tbl_positions AS p LEFT JOIN ( select w1.Position as PositionID, sum( if( w1.status = 2, 1, 0 )) as Booked, sum( if( w1.status = 3, 1, 0 )) as Placed from tbl_workers w1 where w1.status in ( 2, 3 ) and w1.Position > 0 group by PositionID union all select w2.Position2 as PositionID, sum( if( w2.status = 2, 1, 0 )) as Booked, sum( if( w2.status = 3, 1, 0 )) as Placed from tbl_workers w2 where w2.status in ( 2, 3 ) and w2.Position2 > 0 group by PositionID ) as w on p.id = w.positionID group by p.id, p.position
{ "language": "en", "url": "https://stackoverflow.com/questions/7537381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jetty Classpath issues I'm currently running Solr out of a Jetty container that it ships with. It runs correctly when run from the command line via: java -jar start.jar when I'm in the same directory as start.jar. Unfortunately I need to be able to launch jetty from any directory, not just the one that contains start.jar. I've tried many options, such as: java -Dsolr.solr.home=~/solr/ -Djetty.home=~/solr/ -Djetty.logs=~/solr/logs/ -cp ~/solr/start.jar:~/solr/lib/jetty-util-6.1.26-patched-JETTY-1340.jar:~/solr/lib/jetty-6.1.26-patched-JETTY-1340.jar:~/solr/lib/servlet-api-2.5-20081211.jar -jar ~/solr/start.jar ~/solr/etc/jetty.xml Every time I get this backtrace: java.lang.ClassNotFoundException: org.mortbay.xml.XmlConfiguration at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.mortbay.start.Main.invokeMain(Main.java:179) at org.mortbay.start.Main.start(Main.java:534) at org.mortbay.start.Main.start(Main.java:441) at org.mortbay.start.Main.main(Main.java:119) A: Simply changing to the correct directory before calling java.... fixed the problem for me. A: Note that when you run java ... -cp ~/solr/start.jar:... -jar ~/solr/start.jar ~/solr/etc/jetty.xml the -cp option is ignored since you use the -jar option. From man java: -jar When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored. You have two options: * *Keep using the -jar option, but then you need to provide the classpath in the jar manifest file (note that these classpath entries can't be relative to the current path, only relative to the jar-file you're executing) *Skip the -jar option and provide the main class explicitly. A: You're using the ~ as a short cut to the current user's home directory. I'd replace all tilde characters with an absolute path and see if that helps. A: I ran into this in Jan 2014.My issue was that because I ran a Cluster Zookeeper setup from elsewhere, the $SOLR_HOME/lib folder got moved under $SOLR_HOME/cloud-scripts where the zkCli.bat exists.Copied the lib folder back under $SOLR_HOME/ and it works now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Google App Engine Live Updates (Python) I was wondering if it would be possible to write an application using the Google App Engine and Python to create a basic calculator? However, the real question is would it be possible to have the calculator do the math without having to refresh the page? To be more specific, I mean if there is an input box that a formula can be entered into (lets say for example the user inputs 2 + 2) and then the user clicks a submit button or calculate button, can the answer to the inputted problem be solved without the webpage having to refresh itself? If so, would it be possible to go about this without using AJAX? A very brief suggestion on how to go about this or a link to an application and its source code that updates things without refreshing the page would be greatly appreciated! Thanks in advance for your answers! A: To make a calculator in a browser that does not involve a page refresh, your best bet is to learn javascript. Searching google or stackoverflow for javascript tutorials will give you lots of options to work from. You don't need to learn python or App Engine to create the calculator. You could use app engine to serve the javascript, but you wouldn't need to write any python to just serve static content like that. A: Using GAE you provide a real-time update with "Channels" http://code.google.com/appengine/docs/python/channel/ The Channel API creates a persistent connection between your application and Google servers, allowing your application to send messages to JavaScript clients in real time without the use of polling. Interesting enough for your purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use C# example using JsonPath? I'm trying to use JsonPath for .NET (http://code.google.com/p/jsonpath/downloads/list) and I'm having trouble finding an example of how to parse a Json string and a JsonPath string and get a result. Has anyone used this? A: using Newtonsoft.Json.Linq yo can use function SelectToken and try out yous JsonPath Check documentation https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm Object jsonObj = JObject.Parse(stringResult); JToken pathResult = jsonObj.SelectToken("results[0].example"); return pathResult.ToString(); A: The problem you are experiencing is that the C# version of JsonPath does not include a Json parser so you have to use it with another Json framework that handles serialization and deserialization. The way JsonPath works is to use an interface called IJsonPathValueSystem to traverse parsed Json objects. JsonPath comes with a built-in BasicValueSystem that uses the IDictionary interface to represent Json objects and the IList interface to represent Json arrays. You can create your own BasicValueSystem-compatible Json objects by constructing them using C# collection initializers but this is not of much use when your Json is coming in in the form of strings from a remote server, for example. So if only you could take a Json string and parse it into a nested structure of IDictionary objects, IList arrays, and primitive values, you could then use JsonPath to filter it! As luck would have it, we can use Json.NET which has good serialization and deserialization capabilities to do that part of the job. Unfortunately, Json.NET does not deserialize Json strings into a format compatible with the BasicValueSystem. So the first task for using JsonPath with Json.NET is to write a JsonNetValueSystem that implements IJsonPathValueSystem and that understands the JObject objects, JArray arrays, and JValue values that JObject.Parse produces. So download both JsonPath and Json.NET and put them into a C# project. Then add this class to that project: public sealed class JsonNetValueSystem : IJsonPathValueSystem { public bool HasMember(object value, string member) { if (value is JObject) return (value as JObject).Properties().Any(property => property.Name == member); if (value is JArray) { int index = ParseInt(member, -1); return index >= 0 && index < (value as JArray).Count; } return false; } public object GetMemberValue(object value, string member) { if (value is JObject) { var memberValue = (value as JObject)[member]; return memberValue; } if (value is JArray) { int index = ParseInt(member, -1); return (value as JArray)[index]; } return null; } public IEnumerable GetMembers(object value) { var jobject = value as JObject; return jobject.Properties().Select(property => property.Name); } public bool IsObject(object value) { return value is JObject; } public bool IsArray(object value) { return value is JArray; } public bool IsPrimitive(object value) { if (value == null) throw new ArgumentNullException("value"); return value is JObject || value is JArray ? false : true; } private int ParseInt(string s, int defaultValue) { int result; return int.TryParse(s, out result) ? result : defaultValue; } } Now with all three of these pieces we can write a sample JsonPath program: class Program { static void Main(string[] args) { var input = @" { ""store"": { ""book"": [ { ""category"": ""reference"", ""author"": ""Nigel Rees"", ""title"": ""Sayings of the Century"", ""price"": 8.95 }, { ""category"": ""fiction"", ""author"": ""Evelyn Waugh"", ""title"": ""Sword of Honour"", ""price"": 12.99 }, { ""category"": ""fiction"", ""author"": ""Herman Melville"", ""title"": ""Moby Dick"", ""isbn"": ""0-553-21311-3"", ""price"": 8.99 }, { ""category"": ""fiction"", ""author"": ""J. R. R. Tolkien"", ""title"": ""The Lord of the Rings"", ""isbn"": ""0-395-19395-8"", ""price"": 22.99 } ], ""bicycle"": { ""color"": ""red"", ""price"": 19.95 } } } "; var json = JObject.Parse(input); var context = new JsonPathContext { ValueSystem = new JsonNetValueSystem() }; var values = context.SelectNodes(json, "$.store.book[*].author").Select(node => node.Value); Console.WriteLine(JsonConvert.SerializeObject(values)); Console.ReadKey(); } } which produces this output: ["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"] This example is based on the Javascript sample at the JsonPath site: * *Javascript Usage and Example A: For those that don't like LINQ (.NET 2.0): namespace JsonPath { public sealed class JsonNetValueSystem : IJsonPathValueSystem { public bool HasMember(object value, string member) { if (value is Newtonsoft.Json.Linq.JObject) { // return (value as JObject).Properties().Any(property => property.Name == member); foreach (Newtonsoft.Json.Linq.JProperty property in (value as Newtonsoft.Json.Linq.JObject).Properties()) { if (property.Name == member) return true; } return false; } if (value is Newtonsoft.Json.Linq.JArray) { int index = ParseInt(member, -1); return index >= 0 && index < (value as Newtonsoft.Json.Linq.JArray).Count; } return false; } public object GetMemberValue(object value, string member) { if (value is Newtonsoft.Json.Linq.JObject) { var memberValue = (value as Newtonsoft.Json.Linq.JObject)[member]; return memberValue; } if (value is Newtonsoft.Json.Linq.JArray) { int index = ParseInt(member, -1); return (value as Newtonsoft.Json.Linq.JArray)[index]; } return null; } public System.Collections.IEnumerable GetMembers(object value) { System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>(); var jobject = value as Newtonsoft.Json.Linq.JObject; /// return jobject.Properties().Select(property => property.Name); foreach (Newtonsoft.Json.Linq.JProperty property in jobject.Properties()) { ls.Add(property.Name); } return ls; } public bool IsObject(object value) { return value is Newtonsoft.Json.Linq.JObject; } public bool IsArray(object value) { return value is Newtonsoft.Json.Linq.JArray; } public bool IsPrimitive(object value) { if (value == null) throw new System.ArgumentNullException("value"); return value is Newtonsoft.Json.Linq.JObject || value is Newtonsoft.Json.Linq.JArray ? false : true; } private int ParseInt(string s, int defaultValue) { int result; return int.TryParse(s, out result) ? result : defaultValue; } } } Usage: object obj = Newtonsoft.Json.JsonConvert.DeserializeObject(input); JsonPath.JsonPathContext context = new JsonPath.JsonPathContext { ValueSystem = new JsonPath.JsonNetValueSystem() }; foreach (JsonPath.JsonPathNode node in context.SelectNodes(obj, "$.store.book[*].author")) { Console.WriteLine(node.Value); } A: I found that the internal JavaScriptSerializer() can work just fine as long as filtering is not required. Using the dataset and examples from JsonPath Dataset + Examples My source for the JsonPath implementation was GitHub public static string SelectFromJson(string inputJsonData, string inputJsonPath) { // Use the serializer to deserialize the JSON but also to create the snippets var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); serializer.MaxJsonLength = Int32.MaxValue; dynamic dynJson = serializer.Deserialize<object>(inputJsonData); var jsonPath = new JsonPath.JsonPathContext(); var jsonResults = jsonPath.Select(dynJson, inputJsonPath); var valueList = new List<string>(); foreach (var node in jsonResults) { if (node is string) { valueList.Add(node); } else { // If the object is too complex then return a list of JSON snippets valueList.Add(serializer.Serialize(node)); } } return String.Join("\n", valueList); } The function is used as follows. var result = SelectFromJson(@" { ""store"": { ""book"": [ { ""category"": ""fiction"", ""author"": ""J. R. R. Tolkien"", ""title"": ""The Lord of the Rings"", ""isbn"": ""0-395-19395-8"", ""price"": 22.99 } ] } }", "$.store.book[*].author");
{ "language": "en", "url": "https://stackoverflow.com/questions/7537398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: What's the correct way to "flatten" data in mySQL from 3 dimensions to 2? I have 3 tables Labels UserValues Users Labels looks like this: 1|First Name 2|Last Name 3|Favorite Book etc... Users looks like this: 1|[phone_number] 2|[phone_number] etc.... UserValues looks like this: 1| [label_id_for_First_Name] |John | [user_id] 2| [label_id_for_Last_Name] |Smith | [user_id] 3| [label_id_for_Fav_Book] |Moby Dick | [user_id] etc... some users may have not filled in some fields (all are optional except for the phone number that is used as a primary key). I'm stumped as to how I can write a query that would flatten this data to look like: uid |First_Name|Last_Name | Favorite_Book [user_id]|John |Smith | Moby Dick //user has all fields filled in [user_id]|Mary | [null] | Kite Runner //user didn't have a last name The idea is that it would grow in column width for as many columns as there were labels associated with these particular users. I'd like to select on the users and have 1 row per user with all the values going out to the right. I can see how I can do this in several queries, but I was hoping to learn what the right way to do this is (maybe it IS to do it in several queries, but I suspect it's not). TIA. A: If you want to write a query using the current data and giving the result in the example this would be it: SQL coding horror SELECT u.id as user_id , uvfirstname.value as firstname , uvlast_name.value as lastname , uvbook.value as book FROM users u LEFT JOIN uservalues uvfirstname ON (uvfirstname.label_id = (SELECT l1.id FROM label l1 WHERE l1.name = 'First name') AND uvfirstname.user_id = u.id) LEFT JOIN uservalues uvlastname ON (uvlastname.label_id = (SELECT l2.id FROM label l2 WHERE l2.name = 'Last name') AND uvlastname.user_id = u.id) LEFT JOIN uservalues uvbook ON (uvbook.label_id = (SELECT l3.id FROM label l3 WHERE l3.name = 'Fav book') AND uvbook.user_id = u.id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7537400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to insert a column into a matrix, the correct Mathematica way I think Mathematica is biased towards rows not columns. Given a matrix, to insert a row seems to be easy, just use Insert[] (a = {{1, 2, 3}, {4, 0, 8}, {7 , 8, 0}}) // MatrixForm 1 2 3 4 0 8 7 8 0 row = {97, 98, 99}; (newa = Insert[a, row, 2]) // MatrixForm 1 2 3 97 98 99 4 0 8 7 8 0 But to insert a column, after some struggle, I found 2 ways, I show below, and would like to ask the experts here if they see a shorter and more direct way (Mathematica has so many commands, and I could have overlooked one that does this sort of thing in much direct way), as I think the methods I have now are still too complex for such a basic operation. First method Have to do double transpose: a = {{1, 2, 3}, {4, 0, 8}, {7 , 8, 0}} column = {97, 98, 99} newa = Transpose[Insert[Transpose[a], column, 2]] 1 97 2 3 4 98 0 8 7 99 8 0 Second method Use SparseArray, but need to watch out for index locations. Kinda awkward for doing this: (SparseArray[{{i_, j_} :> column[[i]] /; j == 2, {i_, j_} :> a[[i, j]] /; j == 1, {i_, j_} :> a[[i, j - 1]] /; j > 1}, {3, 4}]) // Normal 1 97 2 3 4 98 0 8 7 99 8 0 The question is: Is there a more functional way, that is little shorter than the above? I could ofcourse use one of the above, and wrap the whole thing with a function, say insertColumn[...] to make it easy to use. But wanted to see if there is an easier way to do this than what I have. For reference, this is how I do this in Matlab: EDU>> A=[1 2 3;4 0 8;7 8 0] A = 1 2 3 4 0 8 7 8 0 EDU>> column=[97 98 99]'; EDU>> B=[A(:,1) column A(:,2:end)] B = 1 97 2 3 4 98 0 8 7 99 8 0 A: I think I'd do it the same way, but here are some other ways of doing it: -With MapIndexed newa = MapIndexed[Insert[#1, column[[#2[[1]]]], 2] &, a] -With Sequence: newa = a; newa[[All, 1]] = Transpose[{newa[[All, 1]], column}]; newa = Replace[a, List -> Sequence, {3}, Heads -> True] Interestingly, this would seem to be a method that works 'in place', i.e. it wouldn't really require a matrix copy as stated in Leonid's answer and if you print the resulting matrix it apparently works as a charm. However, there's a big catch. See the problems with Sequence in the mathgroup discussion "part assigned sequence behavior puzzling". A: I usually just do like this: In: m0 = ConstantArray[0, {3, 4}]; m0[[All, {1, 3, 4}]] = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}}; m0[[All, 2]] = {97, 98, 99}; m0 Out: {{1, 97, 2, 3}, {4, 98, 0, 8}, {7, 99, 8, 0}} I don't know how it compare in terms of efficiency. A: I originally posted this as a comment (now deleted) Based on a method given by user656058 in this question (Mathematica 'Append To' Function Problem) and the reply of Mr Wizard, the following alternative method of adding a column to a matrix, using Table and Insert, may be gleaned: (a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}}); column = {97, 98, 99}; Table[Insert[a[[i]], column[[i]], 2], {i, 3}] // MatrixForm giving Similarly, to add a column of zeros (say): Table[Insert[#[[i]], 0, 2], {i, Dimensions[#][[1]]}] & @ a As noted in the comments above, Janus has drawn attention to the 'trick' of adding a column of zeros by the ArrayFlatten method (see here) ArrayFlatten[{{Take[#, All, 1], 0, Take[#, All, -2]}}] & @ a // MatrixForm Edit Perhaps simpler, at least for smaller matrices (Insert[a[[#]], column[[#]], 2] & /@ Range[3]) // MatrixForm or, to insert a column of zeros Insert[a[[#]], 0, 2] & /@ Range[3] Or, a little more generally: Flatten@Insert[a[[#]], {0, 0}, 2] & /@ Range[3] // MatrixForm May also easily be adapted to work with Append and Prepend, of course. A: Your double Transpose method seems fine. For very large matrices, this will be 2-3 times faster: MapThread[Insert, {a, column, Table[2, {Length[column]}]}] If you want to mimic your Matlab way, the closest is probably this: ArrayFlatten[{{a[[All, ;; 1]], Transpose[{column}], a[[All, 2 ;;]]}}] Keep in mind that insertions require making an entire copy of the matrix. So, if you plan to build a matrix this way, it is more efficient to preallocate the matrix (if you know its size) and do in-place modifications through Part instead. A: You can use Join with a level specification of 2 along with Partition in subsets of size 1: a = {{1, 2, 3}, {4, 0, 8}, {7 , 8, 0}} column = {97, 98, 99} newa = Join[a,Partition[column,1],2]
{ "language": "en", "url": "https://stackoverflow.com/questions/7537401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: How to hide css border-right using loop for even number count in cakephp I am using cakephp and here is my sample code below along with the css i am doing <div class="thumbs"> <?php if(!empty($auction['Product']['Image']) && count($auction['Product']['Image']) > 0):?> <?php foreach($auction['Product']['Image'] as $image):?> <?php if(!empty($image['ImageDefault'])) : ?> <span><?php echo $html->link( $html->image('default_images/'.$appConfigurations['serverName'].'/thumbs/'.$image['ImageDefault']['image']), '/img/'.$appConfigurations['currency'].'/default_images/max/'.$image['ImageDefault']['image'], array('class' => 'productImageThumb'), null, false);?> </span> <?php endif; ?> <?php endforeach;?> <?php endif;?> </div> .thumbs span //css for how to display the images { float:left; width:75px; //this displays two images as a thumbnail in a single row margin:12px; border-right:1px solid #d5d5d5; padding:3px; } My problem is i want to do css border-right:none for all the images having count as even numbers. I tried using for loop in the span of my code but not getting the result. Please suggest me how to dynamically do css border-right for only thumb images of odd number count and not for even numbers. A: Add the key to the foreach loop and add a new class to odd images using the key (assuming this is a standard Cake query result where the key reliably increments by one): foreach( $auction['Product']['Image'] as $key => $image ): $odd = ( $key % 2 ) ? ' oddImage' : ''; .... array( 'class' => 'productImageThumb'.$odd ), .... .oddImage { border-right:1px solid #d5d5d5; } (Protip: You don't have to wrap every line of PHP into <?php ... ?> tags. The code will be much more readable if you close the PHP tags only when you need to output pure HTML.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7537404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image Editor Using PHP and Java Script How to Rotate, Edit , Add Text to an image and Save it to local folder like a image editor Based on php and java script. I already tried image rotation in PHP Image Creator. But it reduces the image quality too much. If anybody knows idea to do that please share here. Thanks A: Use canvas. Here is a tutorial for the rotation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: print System.out.println() result in console I start the simulator "Debug As > Blackberry Simulator", the debugger is attached and then I see lots of things when the simulator starts. It includes my println statements too. But i want to see my println statements only, then the debuging will be more easier.Any way? the output i am getting in console is [0.0] JVM: bklt[1] @16945: JvmBacklightEnableFor 30 () [0.0] VM:-DA 0 [0.0] VM:+CR [0.0] VM:-CR=0 [0.0] AM: init [0.0] VM:PISVt=0,h=2e47,id=e44ef6bca97b83b2 [0.0] JVM: bklt[1] @-805309853: JBSC on=1 [0.0] JVM: bklt[1] @-805309853: SC 1 [0.0] JVM: bklt @17007: setTimer 30 [0.0] AM: Starting tier 0 [0.0] VM:NCICv=36 [0.0] AM: Starting net_rim_crypto [0.0] AM: Started net_rim_crypto(2) [0.0] AM: Starting net_rim_tac [0.0] AM: Started net_rim_tac(3) [0.0] AM: Starting net_rim_bb_elt [0.0] VM:NCICv=30 [0.0] VM:NFICv=5 [0.0] VM:NFICv=4 [0.0] VM:NFICv=8 [0.0] VM:NFICv=7 [0.0] VM:NFICv=6 [0.0] AM: Started net_rim_bb_elt(4) [0.0] AM: Starting net_rim_escreen_app [0.0] AM: Started net_rim_escreen_app(5) [0.0] AM: Starting net_rim_tid_spell_check A: Unfortunately there is no way to filter out unwanted console messages. But there is a workaround. Add !!!!!!!!!!!!!! or something like that to the start of your messages, it will help you to find your messages in the whole heap of console output. For instance: System.out.println("!!!!!!!!!!!!!! myVar: " + myVar);
{ "language": "en", "url": "https://stackoverflow.com/questions/7537411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can set location of parent from pop up window opened by iframe. I want to set location of parent window from pop up window opened by iframe. I am writing this line of code in javascript but it is not working. window.opener.parent.location = '../Account/'; A: try window.opener.parent.location.href = '../account/'; A: Should work with window.parent.location.href = '../account/'; A: try some thing like this <b>iframe starts here</b><br><br> <iframe src='iframe1.html'></iframe> <br><br> <b>iframe ends here</b> <script type="text/javascript"> function change_parent_url(url) { document.location=url; } </script> In iframe <a href="javascript:parent.change_parent_url('http://yahoo.com');"> Click here to change parent URL </a> So you can see that child iframe calls parent's function and gives URL
{ "language": "en", "url": "https://stackoverflow.com/questions/7537417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to filter Android logcat by application? How can I filter Android logcat output by application? I need this because when I attach a device, I can't find the output I want due to spam from other processes. A: put this to applog.sh #!/bin/sh PACKAGE=$1 APPPID=`adb -d shell ps | grep "${PACKAGE}" | cut -c10-15 | sed -e 's/ //g'` adb -d logcat -v long \ | tr -d '\r' | sed -e '/^\[.*\]/ {N; s/\n/ /}' | grep -v '^$' \ | grep " ${APPPID}:" then: applog.sh com.example.my.package A: When we get some error from our application, Logcat will show session filter automatically. We can create session filter by self. Just add a new logcat filter, fill the filter name form. Then fill the by application name with your application package. (for example : my application is "Adukan" and the package is "com.adukan", so I fill by application name with application package "com.adukan") A: If you use Eclipse you are able to filter by application just like it is possible with Android Studio as presented by shadmazumder. Just go to logcat, click on Display Saved Filters view, then add new logcat filter. It will appear the following: Then you add a name to the filter and, at by application name you specify the package of your application. A: Edit: The original is below. When one Android Studio didn't exist. But if you want to filter on your entire application I would use pidcat for terminal viewing or Android Studio. Using pidcat instead of logcat then the tags don't need to be the application. You can just call it with pidcat com.your.application You should use your own tag, look at: http://developer.android.com/reference/android/util/Log.html Like. Log.d("AlexeysActivity","what you want to log"); And then when you want to read the log use> adb logcat -s AlexeysActivity That filters out everything that doesn't use the same tag. A: On my Windows 7 laptop, I use 'adb logcat | find "com.example.name"' to filter the system program related logcat output from the rest. The output from the logcat program is piped into the find command. Every line that contains 'com.example.name' is output to the window. The double quotes are part of the find command. To include the output from my Log commands, I use the package name, here "com.example.name", as part of the first parameter in my Log commands like this: Log.d("com.example.name activity1", "message"); Note: My Samsung Galaxy phone puts out a lot less program related output than the Level 17 emulator. A: According to http://developer.android.com/tools/debugging/debugging-log.html: Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above: adb logcat ActivityManager:I MyApp:D *:S The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. * *V — Verbose (lowest priority) *D — Debug *I — Info *W — Warning *E — Error *F — Fatal *S — Silent (highest priority, on which nothing is ever printed) A: Hi I got the solution by using this : You have to execute this command from terminal. I got the result, adb logcat | grep `adb shell ps | grep com.package | cut -c10-15` A: I am working on Android Studio, there is a nice option to get the message using package name. On the "Edit Filter Configuration" you can create a new filter by adding your package name on the "by package name". A: I use to store it in a file: int pid = android.os.Process.myPid(); File outputFile = new File(Environment.getExternalStorageDirectory() + "/logs/logcat.txt"); try { String command = "logcat | grep " + pid + " > " + outputFile.getAbsolutePath(); Process p = Runtime.getRuntime().exec("su"); OutputStream os = p.getOutputStream(); os.write((command + "\n").getBytes("ASCII")); } catch (IOException e) { e.printStackTrace(); } A: This is probably the simplest solution. On top of a solution from Tom Mulcahy, you can further simplify it like below: alias logcat="adb logcat | grep `adb shell ps | egrep '\bcom.your.package.name\b' | cut -c10-15`" Usage is easy as normal alias. Just type the command in your shell: logcat The alias setup makes it handy. And the regex makes it robust for multi-process apps, assuming you care about the main process only. Of coz you can set more aliases for each process as you please. Or use hegazy's solution. :) In addition, if you want to set logging levels, it is alias logcat-w="adb logcat *:W | grep `adb shell ps | egrep '\bcom.your.package.name\b' | cut -c10-15`" A: If you could live with the fact that you log are coming from an extra terminal window, I could recommend pidcat (Take only the package name and tracks PID changes.) A: Suppose your application named MyApp contains the following components. * *MyActivity1 *MyActivity2 *MyActivity3 *MyService In order to filter the logging output from your application MyApp using logcat you would type the following. adb logcat MyActivity1:v MyActivity2:v MyActivity3:v MyService:v *:s However this requires you to know the TAG names for all of the components in your application rather than filtering using the application name MyApp. See logcat for specifics. One solution to allow filtering at the application level would be to add a prefix to each of your unique TAG's. * *MyAppActivity1 *MyAppActivity2 *MyAppActivity3 *MyAppService Now a wild card filter on the logcat output can be performed using the TAG prefix. adb logcat | grep MyApp The result will be the output from the entire application. A: Yes now you will get it automatically.... Update to AVD 14, where the logcat will automatic session filter where it filter log in you specific app (package) A: On the left in the logcat view you have the "Saved Filters" windows. Here you can add a new logcat filter by Application Name (for example, com.your.package) A: What I usually do is have a separate filter by PID which would be the equivalent of the current session. But of course it changes every time you run the application. Not good, but it's the only way the have all the info about the app regardless of the log tag. A: Generally, I do this command "adb shell ps" in prompt (allows to see processes running) and it's possible to discover aplication's pid. With this pid in hands, go to Eclipse and write pid:XXXX (XXXX is the application pid) then logs output is filtered by this application. Or, in a easier way... in logcat view on Eclipse, search for any word related with your desired application, discover the pid, and then do a filter by pid "pid:XXXX". A: you can achieve this in Eclipse logcat by entering the following to the search field. app:com.example.myapp com.example.myapp is the application package name. A: my .bash_profile function, it may be of any use logcat() { if [ -z "$1" ] then echo "Process Id argument missing."; return fi pidFilter="\b$1\b" pid=$(adb shell ps | egrep $pidFilter | cut -c10-15) if [ -z "$pid" ] then echo "Process $1 is not running."; return fi adb logcat | grep $pid } alias logcat-myapp="logcat com.sample.myapp" Usage: $ logcat-myapp $ logcat com.android.something.app A: In Android Studio in the Android Monitor window: 1. Select the application you want to filter 2. Select "Show only selected application" A: Use fully qualified class names for your log tags: public class MyActivity extends Activity { private static final String TAG = MyActivity.class.getName(); } Then Log.i(TAG, "hi"); Then use grep adb logcat | grep com.myapp A: The Android Device Monitor application available under sdk/tools/monitor has a logcat option to filter 'by Application Name' where you enter the application package name. A: On Linux/Un*X/Cygwin you can get list of all tags in project (with appended :V after each) with this command (split because readability): $ git grep 'String\s\+TAG\s*=\s*' | \ perl -ne 's/.*String\s+TAG\s*=\s*"?([^".]+).*;.*/$1:V/g && print ' | \ sort | xargs AccelerometerListener:V ADNList:V Ashared:V AudioDialog:V BitmapUtils:V # ... It covers tags defined both ways of defining tags: private static final String TAG = "AudioDialog"; private static final String TAG = SipProfileDb.class.getSimpleName(); And then just use it for adb logcat. A: I have found an app on the store which can show the name / process of a log. Since Android Studio just puts a (?) on the logs being generated by the other processes, I found it useful to know which process is generating this log. But still this app is missing the filter by the process name. You can find it here. A: The log cat output can be filtered to only display messages from your package by using these arguments. adb com.your.package:I *:s Edit - I spoke to soon. adb com.your.package:v A: to filter the logs on command line use the below script adb logcat com.yourpackage:v A: use first parameter as your application name. Log.d("your_Application_Name","message"); and in LogCat : create Filter ---> Filter Name & by Log Tag: is equal to 'your_Application_Name' it will create new tab for your application. A: Add your application's package in "Filter Name" by clicking on "+" button on left top corner in logcat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "125" }
Q: Superwebsockets Subprotocols I'm working with SuperWebSockets, and the readme.txt for the jsoncommandassembly says: * *Copy this project's output to working directory of SuperWebSocket's running container, SuperWebSocketService, SuperWebSocketWeb or your own container. Well, maybe I'm like serious tired or who knows but what is considered the working container? I've placed it several places and the Assembly.Load causes an exception, file not found. Where should I place the jsoncommandassembly dll? Sorry I'm being dumb.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Routing error in Ruby on Rails 3 I am new to Ruby on Rails I am getting this error uninitialized constant WelcomeController after creating the sample project. I enabled root :to => 'welcome#index' in routes.rb. A: I'm very very new to Rails and also ran into this error while following along with Rails Tutorial by Michael Hartl. The problem I had was that in the config/routes.rb file, I just uncommented the root :to => "welcome#index": # just remember to delete public/index.html. root :to => "welcome#index" but with the structure of the sample_app was that "welcome#index" should be 'pages#home' instead, since everything was originally set up through the "pages" controller. root :to => 'pages#home' It's even right there in the book, but I just overlooked it and spent quite a while afterwards trying to figure out where I went wrong. A: When you say root :to => 'welcome#index' you're telling Rails to send all requests for / to the index method in WelcomeController. The error message is telling you that you didn't create your WelcomeController class. You should have something like this: class WelcomeController < ApplicationController def index # whatever your controller needs to do... end end in app/controllers/welcome_controller.rb. A: Make sure WelcomeController is defined in a file called welcome_controller.rb A: rails generate controller welcome index A: If you not generate the page with name welcome, then just generate the page like: $ rails generate controller pagename index. So then into the: config->routes.rb you should edit root 'welcome#index' to root 'pagename#index' A: Keep this if you want it to be your context root after you generate your welcome parts. Rails.application.routes.draw do root 'welcome#index' end
{ "language": "en", "url": "https://stackoverflow.com/questions/7537424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Design best practice - should an object own what is passed to its constructor? I have the following class: public class SqlCeEventStore: EventStore { private EventStoreDB db; public SqlCeEventStore(EventStoreDB db) { this.db = db; } public void Dispose() { db.Dispose(); } } My problem is this: am I correct in disposing the EventStoreDB in the Dispose method of my class, given that it was passed to it in the constructor (and thus, might conceivably be reused after my class is disposed)? That is, if I dispose it I mandate that the correct usage of my class is: using (var store = new SqlCeEventStore(new EventStoreDB)){ { //... } but I can see this alternative call being used: using (var db = new EventStoreDB()) using (var store = new SqlCeEventStore(db)) { //... } in which case I should not dispose of the EventStoreDB from the SqlCeEventStore class. Are there any arguments for one style or the other? I want to pick one and stick to it, and I'd rather not flip a coin :) A: In general there is no rule to this, but yes I would agree that since the object was created outside your scope and was passed to you, you don't own it. If you had created it, then you should have all rights to do whatever you like to (with documenting the expected behavior for the callers) This is the classical composition vs aggregation stuff. A: If the EventStoreDB is owned by SqlEventStore (ie is part of its composition), it should be constructed by or be merged with the SqlEventStore class. If it has uses outside the scope of the SqlEventStore lifetime then it should be created and disposed by the external code. A: There is no general rule here, and IMHO, there should not be one either. Different objects have different lifespans, and the most general guideline would be to make sure that objects are managed consistently according to their lifespans, and that lifespans are as short as possible. You could try to use the following as a guideline (but don't be afraid to deviate when you need to): Dispose of an object in the same scope as you allocate it. This guideline is suitable for many scenarios, and it is exactly what the using statement simplifies. If you have long-lived objects without an obvious disposal point, don't worry. That's normal. However, ask yourself this: Do I really need this object to live for as long as it does? Is there some other way I can model this to make the lifespan shorter? If you can find another way that makes the lifespan shorter, that generally makes the object more manageable, and should be preferred. But again, there is not any "one true rule" here. A: You can not pick one and stick to it. The user can always choose what ever he wants. However, keep in mind that you are not responsible as a class of disposing objects passed through the constructor. note The coming is really silly to discuss because if you want to impose initiation of the class using *new SqlCeEventStore(new EventStoreDB))* then why don't you remove this EventStoreDB parameter and instantiate the variable db inside your constructor. Workaround There is a workaround -check this: public myClass { //do not make the constructor public //hide it private myClass(EventStoreDB db){ this.db = db; } //make a public constructor that will call the private one in the way you want public myClass(){ this(myClass(new EventStoreDB())); } } A: I would suggest that if one can reasonably imagine situations in which the constructed object would be the last thing in the universe that's interested in the passed-in object, as well as situations in which other things will want to keep using the passed-in object after the constructor is done with it, it may be desirable to have a constructor parameter which specifies whether the new object should take ownership of the object that was passed in. Note that if the constructed object will be taking ownership of the passed-in object, it's important to make certain that object will be disposed even if the constructor throws an exception. One way to do this would be to wrap the constructor call in a routine which will, in a "finally" block, dispose the passed-in object unless the constructor had completed successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Search form using sunspot/solr I'm using sunspot for the first time and i'm trying to setup the search. full text search seems to work fine. however, i have a form with a search box and multiple filters on boolean fields that the user can select. somehow the search box works fine but solr isn't picking up the individual booleans as additional filters. also, when i don't do any search text and just want to search by the boolean fields, nothing happens. any help would be appreciated: this is my controller: @search = Project.search do fulltext params[:search] facet(:master_bedroom) facet(:dining_room) facet(:bath) with(:master_bedroom, params[:mb]) if params[:mb].present? with(:dining_room, params[:dr]) if params[:dr].present? with(:bath, params[:p_bath]) if params[:p_bath].present? end i have the fields in the model: searchable do text :description boolean :dining_room boolean :bath boolean :master_bedroom end and i have the following for my view: <%= form_tag projects_path, :method => :get do %> <%= text_field_tag :search, params[:search] %> <%= check_box_tag :bath, 'true'%> <%= submit_tag "Search", :name => nil %> <% end %> A: There was an error in variable naming.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can i make a div as non selectable from code behind I have my div as follows <div class="menu" id="admindiv" runat="server"> <ul> <li><a href="">welcome to my site<!--[if IE 7]><!--></a><!--<![endif]--> <table> <tr> <td> <ul> <li><a href="Reports.aspx">Reports</a></li> <li><a href="Delete.aspx">Delete</a></li> </ul> </td> </tr> </table> <!--[if lte IE 6]></a><![endif]--> </li> <!--[if lte IE 6]></a><![endif]--> </ul> </div> I would like to enable or disable on a page from code behind, means i would like to make this div as non selectable field on certain conditions. I tried this but i didn't get succeeded protected void Page_Load(object sender, EventArgs e) { admindiv.Attributes.Add("style", "color:gray;"); admindiv.Attributes.Add("disabled", "true"); } A: You can't make a DIV non-selectable. If you want to make the links non-clickable, this is the code-snipt does it: <div class="menu" id="admindiv"> <ul> <li><a href="">welcome to my site<!--[if IE 7]><!--></a><!--<![endif]--> <table> <tr> <td> <ul> <li> <asp:HyperLink ID="Link1" runat="server" Text="Reports" /> </li> <li> <asp:HyperLink ID="Link2" runat="server" Text="Delete" /> </li> </ul> </td> </tr> </table> <!--[if lte IE 6]></a><![endif]--> </li> <!--[if lte IE 6]></a><![endif]--> </ul> </div> AND the code-behind: protected void Page_Load(object sender, EventArgs e) { if(isAdmin) { // check for admin user Link1.NavigateUrl = "Reports.aspx"; Link1.NavigateUr2 = "Delete.aspx"; } else { Link1.NavigateUrl = "javascript:return void;"; Link1.NavigateUr2 = "javascript:return void;"; } } A: Divs can be shown and hidden, but not disabled. If the div is visible its contents will be active unless you disable each item individually. Another option to disabling each control is to create a new div that is transparent but sits on top of the part you want to disable, then just show / hide that div from the code behind. However this is not a security mechanism, as anyone with a browser HTML developer plug-in (like firebug) can remove that div and gain access to the controls. The best way to disable links in ASP.NET is to add an "onclick" event (works with linkbuttons and hyperlinks): LinkButton1.Attributes["OnClick"] = “return false;”;
{ "language": "en", "url": "https://stackoverflow.com/questions/7537435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to increment a variable on a for loop in jinja template? I would like to do something like: variable p is from test.py which is a list ['a','b','c','d'] {% for i in p %} {{variable++}} {{variable}} result output is: 1 2 3 4 A: As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop. You can defeat this behavior by using an object rather than a scalar for 'count': {% set count = [1] %} You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well): {% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #} Or... {% set count = [] %} {% for something-that-loops %} {% set __ = count.append(1) %} <div> Lorem ipsum meepzip dolor... {{ count|length }} </div> {% endfor %} (From comments by @eyettea and @PYB) A: if anyone want to add a value inside loop then you can use this its working 100% {% set ftotal= {'total': 0} %} {%- for pe in payment_entry -%} {% if ftotal.update({'total': ftotal.total + 5}) %}{% endif %} {%- endfor -%} {{ftotal.total}} output = 5 A: Came searching for Django's way of doing this and found this post. Maybe someone else need the django solution who come here. {% for item in item_list %} {{ forloop.counter }} {# starting index 1 #} {{ forloop.counter0 }} {# starting index 0 #} {# do your stuff #} {% endfor %} Read more here: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ A: I was struggle with this behavior too. I wanted to change div class in jinja based on counter. I was surprised that pythonic way did not work. Following code was reseting my counter on each iteration, so I had only red class. {% if sloupec3: %} {% set counter = 1 %} {% for row in sloupec3: %} {% if counter == 3 %} {% set counter = 1 %} {% endif %} {% if counter == 1: %} <div class="red"> some red div </div> {% endif %} {% if counter == 2: %} <div class="gray"> some gray div </div> {% endif %} {% set counter = counter + 1 %} {% endfor %} {% endif %} I used loop.index like this and it works: {% if sloupec3: %} {% for row in sloupec3: %} {% if loop.index % 2 == 1: %} <div class="red"> some red div </div> {% endif %} {% if loop.index % 2 == 0: %} <div class="gray"> some gray div </div> {% endif %} {% endfor %} {% endif %} A: You could use loop.index: {% for i in p %} {{ loop.index }} {% endfor %} Check the template designer documentation. In more recent versions, due to scoping rules, the following would not work: {% set count = 1 %} {% for i in p %} {{ count }} {% set count = count + 1 %} {% endfor %} A: Here's my solution: Put all the counters in a dictionary: {% set counter = { 'counter1': 0, 'counter2': 0, 'etc': 0, } %} Define a macro to increment them easily: {% macro increment(dct, key, inc=1)%} {% if dct.update({key: dct[key] + inc}) %} {% endif %} {% endmacro %} Now, whenever you want to increment the 'counter1' counter, just do: {{ increment(counter, 'counter1') }} A: After 2.10, to solve the scope problem, you can do something like this: {% set count = namespace(value=0) %} {% for i in p %} {{ count.value }} {% set count.value = count.value + 1 %} {% endfor %} A: Just to shed more light into this problem. Jinja2 variables behaves differently from that of conventional scripting languages, you can't modify the variable in a for loop.Hence to bypass this behaviour you can use a dictionary, since you can change the value of the dictionary. **{% set margin={"margin_value":0} %}** {% for lang in language %} <ul> <li style="margin-right: {{ margin.margin_value}}px">{{ lang }}</li> </ul> **{% if margin.update({"margin_value":margin.margin_value + 2}) %} {% endif %}** {% endfor %} In the above code the value of the dictionary is being modified.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "112" }
Q: What does "wrong number of arguments (1 for 0)" mean in Ruby? What does "Argument Error: wrong number of arguments (1 for 0)" mean? A: When you define a function, you also define what info (arguments) that function needs to work. If it is designed to work without any additional info, and you pass it some, you are going to get that error. Example: Takes no arguments: def dog end Takes arguments: def cat(name) end When you call these, you need to call them with the arguments you defined. dog #works fine cat("Fluffy") #works fine dog("Fido") #Returns ArgumentError (1 for 0) cat #Returns ArgumentError (0 for 1) Check out the Ruby Koans to learn all this. A: I assume you called a function with an argument which was defined without taking any. def f() puts "hello world" end f(1) # <= wrong number of arguments (1 for 0) A: You passed an argument to a function which didn't take any. For example: def takes_no_arguments end takes_no_arguments 1 # ArgumentError: wrong number of arguments (1 for 0) A: If you change from using a lambda with one argument to a function with one argument, you will get this error. For example: You had: foobar = lambda do |baz| puts baz end and you changed the definition to def foobar(baz) puts baz end And you left your invocation as: foobar.call(baz) And then you got the message ArgumentError: wrong number of arguments (0 for 1) when you really meant: foobar(baz)
{ "language": "en", "url": "https://stackoverflow.com/questions/7537450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: How can i define PDO_MYSQL in application.ini file I am try to connect mysql to zend appllication but its gives exception : SQLSTATE[28000] [1045] Access denied for user 'user'@'host' (using password: YES) resources.db.adapter = PDO_MYSQL resources.db.isDefaultAdapter = true resources.db.params.host = *host* resources.db.params.username = *user* resources.db.params.password = *password* resources.db.params.dbname = *dbname* Above noted entry is only in application.ini. This code is run on localhost in my PC but not on server. A: You do not have access to login to Mysql server with that username and password. Check in phpMyAdmin if user rdvscoin_main has enough privilege to access the database rdvscoin_corporate. If the Mysql server is on a separate machine check if user can login from the machine where your code is located. A: You need to change the code like this: resources.db.adapter = PDO_MYSQL resources.db.isDefaultAdapter = true resources.db.params.host = *host* (put localhost here assuming server host is also localhost) resources.db.params.username = *user* (put the user name which you used in your database) resources.db.params.password = *password* (put the password you used in your database) resources.db.params.dbname = *dbname* (use the database you are using) Hope it works!
{ "language": "en", "url": "https://stackoverflow.com/questions/7537459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating Some thing @using (Html.BeginForm()) Helpers In Asp.net MVC3 when you write below code , it generates wrapping html itself @using (Html.BeginForm()) { @Html.ValidationMessageFor(model => model.Text) } It generates codes in below format, <form method="post" action="/Feeds"> <!-- Fields Here --> </form> My question in @using (Html.BeginForm()) automatically adds <form> tag at beginning and end, how can i create something like that of my own. I am looking for some thing like below @using (Html.BeginMYCUSTOMDIV()) { I am text inside div } Expected Generated Output <div class="customDivClass"> I am text inside div </div> A: Something along the lines: public class MyDiv : IDisposable { private readonly TextWriter _writer; public MyDiv(TextWriter writer) { _writer = writer; } public void Dispose() { _writer.WriteLine("</div>"); } } public static class MyExtensions { public static MyDiv BeginMYCUSTOMDIV(this HtmlHelper htmlHelper) { var div = new TagBuilder("div"); div.AddCssClass("customDivClass"); htmlHelper.ViewContext.Writer.WriteLine(div.ToString(TagRenderMode.StartTag)); return new MyDiv(htmlHelper.ViewContext.Writer); } } and in the view: @using (Html.BeginMYCUSTOMDIV()) { <span>Hello</span> } generates: <div class="customDivClass"> <span>Hello</span> </div> A: If I'm not mistaken, Html.BeginForm() returns an IDisposable object. When used in the using block, the object's Disposemethod is called, which is the responsible to write the closing tag to the output. how does using HtmlHelper.BeginForm() work? Html.BeginForm() type of extension
{ "language": "en", "url": "https://stackoverflow.com/questions/7537462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to select date from dropdown calender using selenium I have a dropdown calendar and I need to select a date from it using Selenium. I'm using python as my scripting Language. I'm also new to this selenium. A: For the following HTML: <select id="edit-birthday-day" class="form-select" name="birthday[day]"> <option selected="selected" value="">-</option> <option value="1">1</option> <option value="2">2</option> </select> use you can use the following scripting in Python: sel.select("id=edit-birthday-day", "label=2") Please also refer to Selenium Documentation: select ( selectLocator,optionLocator ) Select an option from a drop-down using an option locator. Option locators provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Locator. label=labelPattern matches options based on their labels, i.e. the visible text. (This is the default.) label=regexp:^[Oo]ther value=valuePattern matches options based on their values. value=other id=id matches options based on their ids. id=option1 index=index matches an option based on its index (offset from zero). index=2 If no option locator prefix is provided, the default behaviour is to match on label. Arguments: selectLocator - an element locator identifying a drop-down menu optionLocator - an option locator (a label by default)
{ "language": "en", "url": "https://stackoverflow.com/questions/7537464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to turn on STDOUT.sync in ruby from the command line I have objective-C code that calls ruby scripts and monitors STDOUT. However, ruby does not seem to synchronise STDOUT by default, so I need to put STDOUT.sync = true at the beginning of the script to see output as it happens. Can I do this as a command line option when calling a ruby script? A: You can create a setup file to require before your script. Then call ruby with the -r flag: ruby -r "$HOME/.rubyopts.rb" myscript.rb You can also set the environment variable RUBYOPT to automatically include that file every time you run ruby: export RUBYOPT="-r $HOME/.rubyopts.rb"
{ "language": "en", "url": "https://stackoverflow.com/questions/7537465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Many-to-many associations and REST? Newbie question, you've been warned! I'm trying to implement a sample Rails app with a many-to-many association, people owning movies, and I'm trying to figure out how exactly to implement the UI for it. It's my understanding that REST requires everything to be a resource, so in this case "User" (person), "Movie" and "Possession" (the joint table) (oh, the puns). Now the interesting part, the UX. Let's say I have a user dashboard where all of your movies are listed. Let's say the user wants to add a movie that he owns. How do you do this in REST? It's trivial with a custom action that one could add to the User controller, but the point is not to go beyond the basic 7 REST actions, right? Therefore I'd have to first do a "new" on a movie and then do a "new" on a possession, which are two operations. How do I collapse them into one? Basically I feel I'm not quite understanding how to maintain REST as soon as multiple models are involved and would appreciate a tip. Thanks! A: Happily, Rails has some magic just for this common scenario. Assuming a model like this: class Movie has_many :users, :through => :possessions end Your view: <%= form_for [current_user, Movie.new] do |f| %> <%= f.label :title %> <%= f.text_field :title %> <% end %> Basically this form will POST to MoviesController#create and will pass along current_user.id as a user_id parameter that (the default) MoviesController#create will know to associate with the Movie it creates. Take a look at the documentation for FormBuilder#form_for for more information. You could also do this the other way around, by the way: class User has_many :movies, :through => :possessions accepts_nested_attributes_for :movies # magic! end And the view: <%= form_for current_user |user_form| %> <%= user_form.fields_for current_user.movies.build |movie_fields| %> <%= movie_fields.label :title %> <%= movie_fields.text_field :title %> <% end %> <% end %> In this case the form will submit to UsersController#update and its parameters will look like this: { :id => 123, :movie => { :title => "The Red Balloon" } } ...and the controller will know to create the Movie object. For more information check the documentation for FormHelper#fields_for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rake assets:precompile is slow The command "rake assets:precompile" works very slow for me. Especially on my Amazon EC2 Micro production server which does not have a lot of processor resources. On EC2 I have to wait 1 minute or more during each deployment just for this precompile task alone. Is there a way to make it faster? Previously I used Jammit to compress/minify css and js. Jammit worked nearly 10 times faster on the same web site and servers. A: If you don't need to load the Rails environment, you should disable that with: config.assets.initialize_on_precompile = false EDIT: I've just written a gem to solve this problem, called turbo-sprockets-rails3. It speeds up your assets:precompile by only recompiling changed files, and only compiling once to generate all assets. It would be awesome if you could help me test out the turbo-sprockets-rails3 gem, and let me know if you have any problems. A: There is a bug in Rails 3.1.0 that includes too many files in the precompile process. This could be the reason for the slowness if you have many assets js and css assets. The other is that Sprockets (the gem doing the compilation) is more complex and has to allow for more options - scss, coffeescript and erb. Because of this I suspect it will be slower doing just concatenation and minification. As suggested, you could precompile the files before deploying them if this is still an issue. A: My solution is to exclude application.js .css and any other application related assets from from precompilation. So that i can use rake assets:precompile once to precompile engine related assets only. Then on each deploy i use a simple rake task to build any application related assets and merge them into manifest.yml: namespace :assets do task :precompile_application_only => :environment do require 'sprockets' # workaround used also by native assets:precompile:all to load sprockets hooks _ = ActionView::Base # ============================================== # = Read configuration from Rails / assets.yml = # ============================================== env = Rails.application.assets target = File.join(::Rails.public_path, Rails.application.config.assets.prefix) assets = YAML.load_file(Rails.root.join('config', 'assets.yml')) manifest_path = Rails.root.join(target, 'manifest.yml') digest = !!Rails.application.config.assets.digest manifest = digest # ======================= # = Old manifest backup = # ======================= manifest_old = File.exists?(manifest_path) ? YAML.load_file(manifest_path) : {} # ================== # = Compile assets = # ================== compiler = Sprockets::StaticCompiler.new(env, target, assets, :digest => digest, :manifest => manifest) compiler.compile # =================================== # = Merge new manifest into old one = # =================================== manifest_new = File.exists?(manifest_path) ? YAML.load_file(manifest_path) : {} File.open(manifest_path, 'w') do |out| YAML.dump(manifest_old.merge(manifest_new), out) end end end To specify which assets to compile i use a YAML configuration file (config/assets.yml): eg. --- - site/site.css - admin/admin.css - site/site.js - admin/admin.js
{ "language": "en", "url": "https://stackoverflow.com/questions/7537474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Importing java classes into JSP That's the problem. I developed a web app with NetBeans 7, Tomcat 7 and hsqldb; on my desktop all is Ok. When I upload my java files (.class, .jsp and .jar packages) to my site and try to load a jsp page which imports a class contained in a package (class FunzioniSessione in package it.swlab.util), I get the following error: org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: 6 in the generated java file Only a type can be imported. it.swlab.util.FunzioniSessione resolves to a package An error occurred at line: 7 in the jsp file: /index.jsp FunzioniSessione cannot be resolved to a type 4: <% 5: synchronized(this) 6: { 7: FunzioniSessione funzioniSessione = new FunzioniSessione(); 8: String percorso = config.getServletContext().getRealPath("/"); 9: funzioniSessione.inizializza(session,request,response,percorso,"infocar"); 10: boolean connesso = session.getAttribute("utenteConnesso") != null; An error occurred at line: 7 in the jsp file: /index.jsp FunzioniSessione cannot be resolved to a type 4: <% 5: synchronized(this) 6: { 7: FunzioniSessione funzioniSessione = new FunzioniSessione(); 8: String percorso = config.getServletContext().getRealPath("/"); 9: funzioniSessione.inizializza(session,request,response,percorso,"infocar"); 10: boolean connesso = session.getAttribute("utenteConnesso") != null; Stacktrace: org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:93) org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330) org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:451) org.apache.jasper.compiler.Compiler.compile(Compiler.java:328) org.apache.jasper.compiler.Compiler.compile(Compiler.java:307) org.apache.jasper.compiler.Compiler.compile(Compiler.java:295) org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:565) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:309) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) note The full stack trace of the root cause is available in the Apache Tomcat/5.5.33 logs. To prevent some obvious answers, I add some more information: * *The package containing the class FunzioniSessione (named funzioniComuni.jar) is in the WEB-INF\lib folder *I can't look at the logs as the note in the stacktrace suggests, because I have no access to the logs folder of my provider's Tomcat server. 3 The directive for the import is <%@page import="it.swlab.util.FunzioniSessione"%> I tried also with a ";" at the end (<%@page import="it.swlab.util.FunzioniSessione;"%>) but with no success. I wait for some suggestions. Thank you A: Is the FunzioniSessione on you classpath ? Generally we keep the classes in web-inf\classes which is already onclasspth. Can you ensure the deployment directory has this structure with you class in expected package ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: str_replace not working I want to delete all occurrences of this substring from my html file: <span style="font-size: 12pt;">BLANK PAGE</span> I tried str_replace, thinking that would be a simple solution, but it does not work: $html = str_replace('<span style="font-size: 12pt;">BLANK PAGE</span>', '', $html); Any suggestions? UPDATE: Mystery solved! Thanks to everyone for letting me know that this should work. Turns out the problem had nothing to do with str_replace! I had grabbed the html string from firebug, not realizing that firebug inserts spaces to "prettify" the html. That's why str_replace failed to find this exact pattern. I would ideally like to delete this question, since the problem ended up having nothing to do with str_replace. Is that possible? A: It should work that way. Did you perhaps forget to assign the result back to your variable? $myhtml = str_replace('<span style="font-size: 12pt;">BLANK PAGE</span>', '', $myhtml); A: str_replace() returns the new version - you need to assign it back to the variable (or a new variable): $myhtml = str_replace('<span style="font-size: 12pt;">BLANK PAGE</span>', '', $myhtml); A: my problem was that i was using de str_replace to replace special characters like (á,é,í,ó,ú) and it did not work . the i tried using notepad++ an change the file enconding to utf8-without BOM , uploaded the file to the server and it worked! A: you cannot replace the html tags using str_replace. It replaces the exact occurances only. If you want replace the span text "strip_tags" to remove all the tags and change span text using str_replace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: why i get a different JSON response? I wish to get the following JSON response: {"result": { "id": "226", "ends_at": "2011-06-24 00:00:00", "photo_url": "1308262872.jpg" } } but i only receive this response: { "id": "226", "ends_at": "2011-06-24 00:00:00", "photo_url": "1308262872.jpg" } why don't i get the '"result":' key path? the code I'm using is(rails): def index respond_to do |format| format.json { render :json => @results } end end thanks. A: Try like this: def index respond_to do |format| format.json { render :json => { :result => @results } } end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7537483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding Web Shortcut to iPhone Homescreen? How can I BY CODE add a web shortcut to iPhone HomeScreen? A: There is no API to do this. Your best bet is to do what many web apps do: create something that points at the part of the toolbar where the add to homescreen button exists. And pray Apple doesn't change the position of that button any time soon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Will loadView be called if there is a nib file? If I override the loadView method, loadView will be called whether there is a nib file. If I don't override loadView and there is a nib file, will it be called ? A: Yes, loadView is responsible for loading nib files automatically from known bundles based on the class name of the view controller. If you override loadView and don't call [super loadView], no nibs will be loaded. The UIViewController class will call loadView when its view property is called and is nil. Also note that overriding loadView and calling super is most likely not what you want. loadView is for setting the self.view property, that's it. Everything else should happen in viewDidLoad etc. A: Yes: @implementation iPhoneHomeViewController - (void)loadView { DEBUGLOG(@"view = %@, superview = %@", [self valueForKey:@"_view"], [[self valueForKey:@"_view"] superview]); [super loadView]; } Console: GNU gdb 6.3.50-20050815 (Apple version gdb-1705) (Fri Jul 1 10:50:06 UTC 2011) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "x86_64-apple-darwin".sharedlibrary apply-load-rules all Attaching to process 1671. [Line: 40] -[iPhoneHomeViewController loadView]: view = (null), superview = (null) A: Yes. Load view will be always gets called irrespective of bundle has a Nib or not. loadView will has the job of loading view for UIViewController which can come from any source. So, it look for views in two ways 1. Check the property nibFile which can be set if you have called initWithNibName:bundle: or if you have storyboard - storyboard stores all the views created inside a nib file too 2. If you don't set nib from either of the source then you are planning to create views yourself. In this case you can set this view to view controller's view property later.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: QVector.push_back error error in QVector<LibraryRecord> Library; Library.push_back(LibraryRecord(DateOfIssue, ReturnDate, FIO,tTekct,FName,TText)); error message: no matching function for call to ‘LibraryRecord::LibraryRecord()’ why? Constructor present //constructor LibraryRecord::LibraryRecord(QString pDateOfIssue, QString pReturnDate, QString FIO, QString tTekct, QString fName, QString TTextt) {..} Can you tell me how to fix this? Thanks in advance! A: Unlike the C++ Standard Library containers (e.g. std::vector), the Qt containers require that the value type be default constructible. That is, your type LibraryRecord must also have a default constructor (the constructor that you show, which requires arguments, is not a default constructor). A: Your class must be assignable. It is probably not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to use Calendar in Emulator? I can't see any calendar in Android Emulator. I want to use event functions in Emulator. How can i use Calendar there? Anyone knows how to do this? Thanks in Advance. A: There is no inbuilt facility in android emulator for calender control. You can create your custom Calender control. For More information about Custom Calender follow below link CALENDER UI
{ "language": "en", "url": "https://stackoverflow.com/questions/7537494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert special character to Image(Smiley) Possible Duplicate: webserivce messages in listview with smileys I created a Db and added 4 fields to it. 1. ID , 2. Position, 3. Special Character 4. URL. So I was able to display the corresponding special character when clicked. when I submit how can I convert that special character into smiley image. I tried to use functions like "Contains()" and "Replace". But nothing worked when I submitted the message to list view. I am listing messages in list view from web service. I get the same special character and text. I don get the image instead of special character. How can I convert special character into smiley image. I store all the images in drawable folder. A: First Thing :Using ListAdapter you can achieve this Refer : http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html And Second : You need to programatically decide which icon to replay with which special character. In List Adapter you will have textview + icon. A: Another method would be to use the webview. And create a html string and replace your special characters with image tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to redirect an user to the same page in which he browsed after login drupal i am working on a website with drupal which has a lot of user restriction pages. when a user is guest and he need to access a webpage he will be asked for user name and password while he logged in he is redirected to the main page or account page .can i make the user to redirect to he same page not to the front page or account page, A: If you are rendering a login link in your template file, you can do something like this: print l("Login","user/login",array('query' => drupal_get_destination())); If you would like a 'code-less' approach, then please checkout the Rules module. Once enabled navigate to /admin/rules/trigger/add and create a 'triggered rule', for example: * *Label: Redirect User Back to Original Page After Logging In *Event: User -> User Has Logged In Then click 'Save Changes'... then click 'Add an action'... Select an action to add: System -> Page Redirect Here you can set 'php evaluation' to: echo implode("/",arg()); That will redirect user back to the page they were on before they logged in. Be careful not to redirect a user to the following paths: * *user/login *user/register *logout A: You can redirect the user by using the action and trigger first go to site configuration and then select action where you can define your action. For ex if you want to redirect the user after login : select redirect to url and hit the create button. Then go to site building and click on trigger (if have installed it, this module comes up with drupal). Where you will find tabs like cron , user. According to your need select tab and apply your action and assign it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Issue in the Assets folder I had an issue where a font didnt work and it gave me a FC. So I put the font file into the sdcard, and used CreateFromFile in the typeface and the font worked! Here is the code I used for the Assets folder: holder.tv_SuraName =(TextView)convertView.findViewById(R.id.Start_Name); holder.tv_SuraName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), "suralist_font.ttf")); But I changed the code to this and it worked: holder.tv_SuraName = (TextView)convertView.findViewById(R.id.Start_Name); Typeface Font = Typeface.createFromFile(new File(Environment.getExternalStorageDirectory()+"/asd.ttf")); Does this mean I have a problem in the Assets folder? How can I fix this? Thanks A: AssetManager assetManager1 = getApplicationContext().getAssets(); Typeface tf1 = Typeface.createFromAsset(assetManager1, "James_Fajardo.ttf"); and used in textview like urTextView.setTypeface(tf1, Typeface.BOLD); hope useful for u. A: see this Typeface font0 = Typeface.createFromAsset(getAssets(),"fonts/AmericanDream.ttf"); tv1.setTypeface(font0); here fonts (folder in assets) folder containing AmericanDream.ttf file inside. like:assets-->fonts-->AmericanDream.ttf i hope this will help u.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery form submit not working in some reason if I use this code it sends the form in normal way not with jquery? What could be the problem? thanks <script> $(document).ready(function() { $("form#formi").submit(function() { $(":text, textarea").each(function() { if ($(this).val() === "") { $('p#error').fadeIn(1000); var tyhjia = true; } }); if (tyhjia == true) { // tyhjia on , joten ei jatketa } else { // we want to store the values from the form input box, then send via ajax below var fname = $('#name').attr('value'); var lname = $('#email').attr('value'); $.ajax({ type: "POST", url: "laheta-viesti", data: "name=" + fname + "& email=" + lname, success: function() { $('form#formi').hide(); $('p#valmista').fadeIn(1000); } }); } return false; }); }); </script> A: Errors in your javascript are the common cause for this behavior. For example you have defined the tyhjia variable inside the anonymous callback and try to use it outside. I have tried to clean your code a little: <script type="text/javascript"> $(document).ready(function() { $('form#formi').submit(function() { var tyhjia = false; $(':text, textarea').each(function() { if($(this).val() === '') { $('p#error').fadeIn(1000); tyhjia = true; } }); if (tyhjia == true) { // tyhjia on , joten ei jatketa } else { // we want to store the values from the form input box, then send via ajax below var fname = $('#name').val(); var lname = $('#email').val(); $.ajax({ type: 'POST', url: 'laheta-viesti', data: { name: fname, email: lname }, success: function() { $('form#formi').hide(); $('p#valmista').fadeIn(1000); } }); } return false; }); }); </script> Of course there could be some other errors left. Use FireBug or Chrome Developer Tool and inspect the console for any possible errors reported. And by the way for doing validation, which is what apparently you are trying to do here, I would very strongly recommend you the jquery validate plugin. A: if you want the jquery behavior to replace the default behavior completely, you must explicitly tell it to not do the default behavior like this: $(document).ready(function(){ $("form#formi").submit(function(e) { e.preventDefault(); notice that two lines of code changed - you must get "e" which is a common abbreviation for "event" from the function as a parameter, then tell it not to perform the default behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: iOS: How to read an audio file into a float buffer I have a really short audio file, say a 10th of a second in (say) .PCM format I want to use RemoteIO to loop through the file repeatedly to produce a continuous musical tone. So how do I read this into an array of floats? EDIT: while I could probably dig out the file format, extract the file into an NSData and process it manually, I'm guessing there is a more sensible generic approach... ( that eg copes with different formats ) A: This is the code I have used to convert my audio data (audio file ) into floating point representation and saved into an array. -(void) PrintFloatDataFromAudioFile { NSString * name = @"Filename"; //YOUR FILE NAME NSString * source = [[NSBundle mainBundle] pathForResource:name ofType:@"m4a"]; // SPECIFY YOUR FILE FORMAT const char *cString = [source cStringUsingEncoding:NSASCIIStringEncoding]; CFStringRef str = CFStringCreateWithCString( NULL, cString, kCFStringEncodingMacRoman ); CFURLRef inputFileURL = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, str, kCFURLPOSIXPathStyle, false ); ExtAudioFileRef fileRef; ExtAudioFileOpenURL(inputFileURL, &fileRef); AudioStreamBasicDescription audioFormat; audioFormat.mSampleRate = 44100; // GIVE YOUR SAMPLING RATE audioFormat.mFormatID = kAudioFormatLinearPCM; audioFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat; audioFormat.mBitsPerChannel = sizeof(Float32) * 8; audioFormat.mChannelsPerFrame = 1; // Mono audioFormat.mBytesPerFrame = audioFormat.mChannelsPerFrame * sizeof(Float32); // == sizeof(Float32) audioFormat.mFramesPerPacket = 1; audioFormat.mBytesPerPacket = audioFormat.mFramesPerPacket * audioFormat.mBytesPerFrame; // = sizeof(Float32) // 3) Apply audio format to the Extended Audio File ExtAudioFileSetProperty( fileRef, kExtAudioFileProperty_ClientDataFormat, sizeof (AudioStreamBasicDescription), //= audioFormat &audioFormat); int numSamples = 1024; //How many samples to read in at a time UInt32 sizePerPacket = audioFormat.mBytesPerPacket; // = sizeof(Float32) = 32bytes UInt32 packetsPerBuffer = numSamples; UInt32 outputBufferSize = packetsPerBuffer * sizePerPacket; // So the lvalue of outputBuffer is the memory location where we have reserved space UInt8 *outputBuffer = (UInt8 *)malloc(sizeof(UInt8 *) * outputBufferSize); AudioBufferList convertedData ;//= malloc(sizeof(convertedData)); convertedData.mNumberBuffers = 1; // Set this to 1 for mono convertedData.mBuffers[0].mNumberChannels = audioFormat.mChannelsPerFrame; //also = 1 convertedData.mBuffers[0].mDataByteSize = outputBufferSize; convertedData.mBuffers[0].mData = outputBuffer; // UInt32 frameCount = numSamples; float *samplesAsCArray; int j =0; double floatDataArray[882000] ; // SPECIFY YOUR DATA LIMIT MINE WAS 882000 , SHOULD BE EQUAL TO OR MORE THAN DATA LIMIT while (frameCount > 0) { ExtAudioFileRead( fileRef, &frameCount, &convertedData ); if (frameCount > 0) { AudioBuffer audioBuffer = convertedData.mBuffers[0]; samplesAsCArray = (float *)audioBuffer.mData; // CAST YOUR mData INTO FLOAT for (int i =0; i<1024 /*numSamples */; i++) { //YOU CAN PUT numSamples INTEAD OF 1024 floatDataArray[j] = (double)samplesAsCArray[i] ; //PUT YOUR DATA INTO FLOAT ARRAY printf("\n%f",floatDataArray[j]); //PRINT YOUR ARRAY'S DATA IN FLOAT FORM RANGING -1 TO +1 j++; } } }} A: I'm not familiar with RemoteIO, but I am familiar with WAV's and thought I'd post some format information on them. If you need, you should be able to easily parse out information such as duration, bit rate, etc... First, here is an excellent website detailing the WAVE PCM soundfile format. This site also does an excellent job illustrating what the different byte addresses inside the "fmt" sub-chunk refer to. WAVE File format * *A WAVE is composed of a "RIFF" chunk and subsequent sub-chunks *Every chunk is at least 8 bytes *First 4 bytes is the Chunk ID *Next 4 bytes is the Chunk Size (The Chunk Size gives the size of the remainder of the chunk excluding the 8 bytes used for the Chunk ID and Chunk Size) *Every WAVE has the following chunks / sub chunks * *"RIFF" (first and only chunk. All the rest are technically sub-chunks.) *"fmt " (usually the first sub-chunk after "RIFF" but can be anywhere between "RIFF" and "data". This chunk has information about the WAV such as number of channels, sample rate, and byte rate) *"data" (must be the last sub-chunk and contains all the sound data) Common WAVE Audio Formats: * *PCM *IEEE_Float *PCM_EXTENSIBLE (with a sub format of PCM or IEEE_FLOAT) WAVE Duration and Size A WAVE File's duration can be calculated as follows: seconds = DataChunkSize / ByteRate Where ByteRate = SampleRate * NumChannels * BitsPerSample/8 and DataChunkSize does not include the 8 bytes reserved for the ID and Size of the "data" sub-chunk. Knowing this, the DataChunkSize can be calculated if you know the duration of the WAV and the ByteRate. DataChunkSize = seconds * ByteRate This can be useful for calculating the size of the wav data when converting from formats like mp3 or wma. Note that a typical wav header is 44 bytes followed by DataChunkSize (this is always the case if the wav was converted using the Normalizer tool - at least as of this writing). A: Update for Swift 5 This is a simple function that helps get your audio file into an array of floats. This is for both mono and stereo audio, To get the second channel of stereo audio, just uncomment sample 2 import AVFoundation //.. do { guard let url = Bundle.main.url(forResource: "audio_example", withExtension: "wav") else { return } let file = try AVAudioFile(forReading: url) if let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: false), let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(file.length)) { try file.read(into: buf) guard let floatChannelData = buf.floatChannelData else { return } let frameLength = Int(buf.frameLength) let samples = Array(UnsafeBufferPointer(start:floatChannelData[0], count:frameLength)) // let samples2 = Array(UnsafeBufferPointer(start:floatChannelData[1], count:frameLength)) print("samples") print(samples.count) print(samples.prefix(10)) // print(samples2.prefix(10)) } } catch { print("Audio Error: \(error)") } A: You can use ExtAudioFile to read data from any supported data format in numerous client formats. Here is an example to read a file as 16-bit integers: CFURLRef url = /* ... */; ExtAudioFileRef eaf; OSStatus err = ExtAudioFileOpenURL((CFURLRef)url, &eaf); if(noErr != err) /* handle error */ AudioStreamBasicDescription format; format.mSampleRate = 44100; format.mFormatID = kAudioFormatLinearPCM; format.mFormatFlags = kAudioFormatFormatFlagIsPacked; format.mBitsPerChannel = 16; format.mChannelsPerFrame = 2; format.mBytesPerFrame = format.mChannelsPerFrame * 2; format.mFramesPerPacket = 1; format.mBytesPerPacket = format.mFramesPerPacket * format.mBytesPerFrame; err = ExtAudioFileSetProperty(eaf, kExtAudioFileProperty_ClientDataFormat, sizeof(format), &format); /* Read the file contents using ExtAudioFileRead */ If you wanted Float32 data, you would set up format like this: format.mFormatID = kAudioFormatLinearPCM; format.mFormatFlags = kAudioFormatFlagsNativeFloatPacked; format.mBitsPerChannel = 32;
{ "language": "en", "url": "https://stackoverflow.com/questions/7537505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: In C++ if a pointer is returned and immediately dereferenced, will the two operations be optimized away? In C++ if I get and return the address of a variable and the caller then immediately dereferences it, will the compiler reliably optimize out the two operations? The reason I ask is I have a data structure where I'm using an interface similar to std::map where find() returns a pointer (iterator) to a value, and returns NULL (there is no trivial .end() equivalent) to indicate that the value has not been found. I happen to know that the variables being stored are pointers, so returning NULL works fine even if I returned the value directly, but it seems that returning a pointer to the value is more general. Otherwise if someone tried to store an int there that was actually 0 the data structure would claim it isn't there. However, I'm wondering if there's even any loss in efficiency here, seeing as the compiler should optimize away actions that just undo the effect of each other. The problem is that the two are separated by a function return so maybe it wouldn't be able to detect that they just undo each other. Lastly, what about having one private member function that just returns the value and an inline public member function that just takes the address of the value. Then at least the address/dereference operations would take place together and have a better chance of being optimized out, while the whole body of the find() function is not inlined. private: V _find(key) { ... // a few dozen lines... } public: inline V* find(key) { return &_find(key); } std::cout << *find(a_key); This would return a pointer to a temporary, which I didn't think about. The only thing that can be done similar to this is to do a lot of processing in the _find() and do the last step and the return of the pointer in find() to minimize the amount of inlined code. private: W* _find(key) { ... // a few dozen lines... } public: inline V* find(key) { return some_func(_find(key)); // last steps on W to get V* } std::cout << *find(a_key); Or as yet another responder mentioned, we could return a reference to V in the original version (again, not sure why we're all blind to the trivial stuff at first glance... see discussion.) private: V& _find(key) { ... // a few dozen lines... } public: inline V* find(key) { return &_find(key); } std::cout << *find(a_key); A: _find returns a temporary object of type V. find then attempts to take the address of the temporary and return it. Temporary objects don't last very long, hence the name. So the temporary returned by _find will be destroyed after getting its address. And therefore find will return a pointer to a previously destroyed object, which is bad. A: I've seen it go either way. It really depends on the compiler and the level optimization. Even when it does get inlined, I've seen cases where the compiler will not optimize this out. The only way to see if it does get optimized out it is to actually look at the disassembly. What you should probably do is to make a version where you manually inline them. Then benchmark it to see if you actually get a noticeable performance gain. If not, then this whole question is moot. A: Your code (even in its second incarnation) is broken. _find returns a V, which find destroys immediately before returning its address. If _find returned a V& to an object that outlives the call (thus producing a correct program), then the dereference would be a no-op, since a reference is no different to a pointer at the machine code level.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: If radio streaming's connection is bad, What have to do next? I made Radio Streaming Iphone App. And submit to itunes app stroe. But they rejected my app. This is the reason. 2.2: Apps that exhibit bugs will be rejected When the user taps on a radio, an alert is displayed stating the connection is lost and no further action can be produced. Yes, If the connection failed, I let the connection bad message appear to screen. But they demand that there should be further action. Do you think What further action is needed? Did you use Wunder Radio or Tunein Radio? These app did same action if the connection failed. Only shows connection error messase. What should I do? A: Your best bet here is to produce better user experience when connection is lost, has failed or was interrupted. I mean you should implement a mechanism visible to user that tries to reestablish connection with your streaming server based on network condition changes. Also it would be good if you allow your users to trigger that action from the alert view you mentioned, e.g. "Connection is lost. Would you like to retry" + no/yes. A good place to start with is adding Reachability to your project (Apple has demo code which uses it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7537508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combining HTML form data with multi-friend selector Having a heck of a time trying to figure out how to do this. I'm trying to combine an HTML form of my making with a multi-friend selector so that people can, for example, choose an item with radio buttons, enter some text in a textarea and then use a multi-friend selector. The form would store the items from my html form in a database while also sending out the request to the selected friend(s). I can't seem to find a way to combine FB's selector with my form so that, upon submission, I get POST info that combines the user ID's selected with the choices from my form. Is this possible using any of FB's SDK selectors, or do I have to roll my own? A: You should use the from the apprequests dialog from the javascript sdk. It will return an array called request_ids that you can use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: netbeans optimize disk usage Is there some way to optimize the Netbeans IDE for PHP (and Symfony)? It's very good with code hinting, debugging etc, but the downside is that while writing code, the disk works intensively all the time which is disturbing and besides the editor slows down slightly because of the code hinting. I have 8GB memory, so it would be quite sufficient for all Netbeans needs. I mean, is it possible to somehow limit the disk usage but without limiting the code hinting? E,g, make it load all code hints to memory. A: Here is a workaround which solves the problematic symptoms, i.e. the NetBeans editor now works without small delays from code hinting and the disk is quiet. I installed RAMDisk with 500MB capacity. Then I moved the .netbeans folder with user files to this RAMDisk, as described in wiki.netbeans.org/FaqWhatIsUserdir. Just FYI, moving the project folder itself made no difference, only .netbeans folder was necessary to move. A: Try to deactivate the Local History plugin, maybe it is causing the high disk usage. (Be careful if you don't have any vcs) Although I've never have a problem with Netbeans and disk usage, maybe your disk is broke. A: Kudos to @camcam for answering his own question and posting the RAM disk suggestion. In case there are other Mac users out there who want to do this on a Mac, here are instructions: 1) Create a 500MB RAM disk: diskutil erasevolume HFS+ 'NetBeansRAMDisk' `hdiutil attach -nomount ram://1048576` 2) Locate the NetBeans application in the Finder, control-click on it and select "Show Package Contents" 3) Add this line to Contents/Resources/NetBeans/etc/netbeans.conf: netbeans_default_cachedir="/Volumes/NetBeansRAMDisk" (Note: the cachedir option was added in NetBeans 7.1.) For more info, see: * *http://bogner.sh/2012/12/os-x-create-a-ram-disk-the-easy-way/ *http://wiki.netbeans.org/FaqAlternateUserdir A: I have been using NetBeans since version 3.x I have never seen it access the disk all the time. I have regularly ~20 projects open with ~350.000 LOC You should first make sure it's actually NetBeans that does the disk access (on Windows you can do this with ProcessExplorer, don't know about Linux). If it's really NetBeans, you could try to give it more memory to cache more data in memory. See the NetBeans FAQ for details And of course make sure your system is not swapping because you have too many programs open (even though it's very unlikely with 8GB RAM but not unseen...). If you already configured NetBeans to use more memory, maybe you gave it too much and that's why the system is swapping (just a thought). Is your project stored in Subversion? Do you use TortoiseSVN? With he default installation TortoiseSVN has a background process that caches information about the status of your versioned files. I have seen that scanning the whole harddisk in the background...
{ "language": "en", "url": "https://stackoverflow.com/questions/7537513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How To Download a File Only If It Has Been Updated I am downloading image from the internet in SD card. First to Check the file is exist in SD Card if no then download the file. if file is already in the SD-card the check the last modified date of existing file and compare it with server file . If server image file date is latest than SD-card file then download the file otherwise as it return the file. I Have did it.The file gets downloaded in SD-card, I have to checked it, is this a write way to achieve this task or is their any other way to do the same task. So could you help me regarding same. here is my code: package com.test; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import java.net.URLConnection; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Set; /*import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; */ import android.app.Activity; import android.graphics.Bitmap; public class FileChache { File sdDir; public FileChache(Activity activity) { // Find the directry to save cache image //Gets the Android external storage directory.---> getExternalStorageState() //MEDIA_MOUNTED if the media is present and mounted at its mount point with read/write access. String sdState = android.os.Environment.getExternalStorageState(); if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) { sdDir=new File(android.os.Environment.getExternalStorageDirectory(),"sa"); } else sdDir=activity.getCacheDir(); if(!sdDir.exists()) sdDir.mkdirs(); } public File getFile(String url) { //identify images by hashcode String filename= String.valueOf(url.hashCode()); System.out.println("The File name is:"+filename); // Check whether the file is exist in SD Card File f= new File(sdDir, filename); Date fileDate = new Date(f.lastModified()); System.out.println("The file date is:"+fileDate.toGMTString()); // Check whether the file is exist in SD Card if(!f.exists()) { return f; } else { //Check the last update of file File file= new File(filename); Date date= new Date(f.lastModified()); System.out.println("The last Modified of file is:"+date.toGMTString()); /*HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url);*/ try { URL urll = new URL(url); String ss= String.valueOf(urll.hashCode()); URLConnection conn= urll.openConnection(); Map map = conn.getHeaderFields(); Set set = map.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { System.out.println("The Data is :"+iterator.next()); } String header=conn.getHeaderField("Last-Modified"); System.out.println("The header is:"+header); long header1=conn.getIfModifiedSince(); Date aaa= new Date(header1); System.out.println("The getIFLastmodifiedSince is:----"+aaa); Date ServerDate_timeStamp = new Date(header); System.out.println("The headerDate(The serverDate_Timestamp) is:"+ServerDate_timeStamp); long filemodifiedDate= f.lastModified(); System.out.println("The last(Long) modified is:"+filemodifiedDate); Date SD_cardFileModifiedDate = new Date(filemodifiedDate); System.out.println("File file Modified Date Date is:"+ SD_cardFileModifiedDate); if(SD_cardFileModifiedDate.before(ServerDate_timeStamp)) { File ff= new File(sdDir,ss); return ff; } else { return f; } } catch(Exception e) { e.printStackTrace(); } } return null; } public void writeFile(Bitmap bmp, File f) { FileOutputStream out = null; try { out = new FileOutputStream(f); bmp.compress(Bitmap.CompressFormat.PNG, 80, out); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null ) out.close(); } catch(Exception ex) {} } } } /*File f= new File(sdDir,filename); System.out.println("***The last modified time of file is:****"+f.lastModified()); Date d= new Date(f.lastModified()); System.out.println("The lst modified Date is:"+d.toGMTString()); Calendar calendar = Calendar.getInstance(); Date mNew_timeStamp = calendar.getTime(); System.out.println("*****new Time_Stamp:*****"+mNew_timeStamp.toGMTString()); if(f.exists()) { System.out.println("The file is exist"); } else { System.out.println("It does not exist"); }*/ //if(header) // System.out.println(conn.getHeaderFieldKey(j)+":"+ header); /*HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget);*/
{ "language": "en", "url": "https://stackoverflow.com/questions/7537519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Handling a lot of data in Java servlet what I am trying to do is reading the latest statuses from all my facebook friends using graph api ,it takes too long , I am getting all my friends for facebook as json and I read the latest statuses from them , what I am getting is timeout , I know it will take too long to do , but what the efficient way to handle such thing? A: break that into batches and probably do it in separate threads (since most of this will be IO work).
{ "language": "en", "url": "https://stackoverflow.com/questions/7537523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pass an object between multiple classes? Java public class FooClass { BarClass bar = null; int a = 0; int b = 1; int c = 2; public FooClass(BarClass bar) { this.bar = bar; bar.setFoo(this); } } public class BarClass { FooClass foo = null; public BarClass(){} public void setFoo(FooClass foo) { this.foo = foo; } } elsewhere... BarClass theBar = new BarClass(); FooClass theFoo = new FooClass(theBar); theFoo.a //should be 0 theBar.foo.a = 234; //I change the variable through theBar. Imagine all the variables are private and there are getters/setters. theFoo.a //should be 234 <----- How can I pass an object to another class, make a change, and have that change appear in the original instance of the first object? or How can I make a cycle where one change to a class is reflected in the other class? A: That's already exactly how objects work in Java. Your code already does what you want it to. When you pass theBar to the FooClass constructor, that's passing the value of theBar, which is a reference to a BarClass object. (theBar itself is passed by value - if you wrote foo = new FooClass(); in the BarClass constructor, that wouldn't change which object theBar referred to. Java is strictly pass-by-value, it's just that the values are often references.) When you change the value within that object using theBar.foo.a, then looking at the value of a again using theFoo.a will see the updated value. Basically, Java doesn't copy objects unless you really ask it to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WP7 Changing 1 layout element based on another Having no luck here trying to find a solution to this. I've set up a looping selector based on this guide. (I also used the ListLoopingDataSource class in Part 2 in order to have strings in my looping list). What I want to be able to do is then change another element (an image box/placeholder) on my layout, based on what is currently selected in the looping selector. No real idea how to do this, the onSelectionChanged event is kind of abstracted and not really useful? I'm not sure how to programmatically change images either, it doesn't look like I can access a resource from the code base, only from the xaml. Any help/suggestions would be greatly appreciated. A: I found that I could do this by using binding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why the conflicting variables? I'm getting conflicting results between the facebook javascript SDK and the python requesthandler variables. The Javascript SDK says my user is not logged in, which is correct, while my template variable that comes from the base request handler says that my user is logged in and displays the name of the user. Is there enough info to tell what is wrong or should I paste the code I think is relevant here? A link to the login page that has the error is here. The example I used is called the runwithfriends demo app from facebook and everything with that app worked except using the logic from the app just from a website without requiring the user to be in the iframe of the app. Plus I can't seem to get the real-time API working. I can only save userID and not refresh user data - why? I have the code but I'm not sure what's most relevant but here's some of the request handler, the relevant code is basically exactly the same as the one from the demo app: def render(self, name, **data): logging.debug('render') """Render a template""" if not data: logging.debug('no data') data = {} data[u'js_conf'] = json.dumps({ u'appId': facebookconf.FACEBOOK_APP_ID, u'canvasName': facebookconf.FACEBOOK_CANVAS_NAME, u'userIdOnServer': self.user.id if self.user else None, }) data[u'logged_in_user'] = self.user #variable that is the problem data[u'message'] = self.get_message() data[u'csrf_token'] = self.csrf_token data[u'canvas_name'] = facebookconf.FACEBOOK_CANVAS_NAME self.response.out.write(template.render( os.path.join( os.path.dirname(__file__), 'templates', name + '.html'), data)) And even more strange, I can also get the application in a state where the javascript SDK says the user is logged in and the template variable logged_in_user says otherwise. Why are the variables conflicting? Update: Here are screenshots from the strange login flow. I can go to my page and my name from facebook appears: Then when I go to next page it also looks alright and has my name But if I log out then I gets in impossible state: my name + logged out How can I resolve this strange conflict between js and back-end? Update: Since I only have this problem for one of my apps I can take what works from my other app and integrate. This page seems to work from my other app: http://cyberfaze.appspot.com/file/20985 A: Your 'user' is probably referring to the Django user not the Facebook user. Make sure you synchronize the two accounts correctly using a custom authentication backend. It's possible that the accounts get out of sync i.e. if the user switches browsers. Keep in mind that the Facebook Python SDK will stop working after October 1st unless they update it to Oauth2.0 which is unlikely. I just updated django-facebook-graph to work with the new authentication flow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: opencart - Increase field size of address in table setting - config_address how to increase field size of address in table setting --> config_address ? Now i see in structure of config_address is Type : TEXT in phpMyadmin , so i need change from TEXT to LONG TEXT ? A: LONGTEXT can hold up to 2^32 bytes, as specified in the mysql data type storage requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is Graphviz the best tool for this type of graph? I want to create a graph like the one shown below... but way too complex. I want to use separate images for each of the square nodes and the same image for each of the circle nodes. I want to know whether using GraphViz is the best option or are there any other options? Also, I would like to know if I can create a template node in GraphViz for the circle one and reuse it? I don't want to specify the attributes like image, shape, etc. again and again. A: Sure, here's the code to draw the graph in your Question (and which is shown rendered by dot, below). digraph g { rankdir = TB; bgcolor = white; edge[arrowsize=.7, color=black]; node[shape=box, color=black] {rank=same; a, b, c}; {rank=same; d, e, f}; {rank=same; g, h}; {rank=same; i, j, k}; d[color=blue; shape=circle]; e[color=blue; shape=circle]; k[color=blue; shape=circle]; a -> d; b -> d; b -> e; c -> e; d -> g; e -> h; d -> i; d -> j; j -> k; h -> k; k -> f; } * *the first line digraph is for directed graph (for graphs in which the edges have a direction). *The fourth and fifth lies above set default attributes for edges and nodes, respectively. In other words, once you've done this, you only need to style (include attribues + values) nodes (or edges) which you want to style differently than the default values. You can have more than one node "template" by creating subgraphs, or discrete groups nodes (see the dot Manual). *rank=same allows you to specifiy a group of nodes having the same vertical position (provided rankdir is set to TB, which meant "top-to-bottom"). *By default, the node name (e.g., a, b, c in my graph) is used as the node's label. If you don't want this shown in the rendered graph, just set label="" A: Graphviz is definitely appropriate for what you are asking. The main graphviz.org site appears to be down for the moment, but someone has kindly mirrored the gallery examples (with source) to Flickr. http://www.flickr.com/photos/kentbye/sets/72157601523153827/ As far as I am aware, you cannot create "templates", but you can do something like this for the circles: node[shape=circle, color=white, style=solid]; node1;node2;node3; This will define a node (think of it as a "state" when evaluating the file line-by-line) and then you can define your circle nodes in that "state" before switching to your rectangles. Depending on your platform, you may also be able to import your .dot file and fine-tune it for publication. There are also a large number of generators and convertors for the format. Mind you, if you are working on Mac OS X 10.7 "Lion", I have not been able to find or build a working version of Graphviz yet. In which case I would say it is not yet appropriate for your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Length of strings in unicode are different How come the length of the following strings is different although the number of characters in the strings are the same echo strlen("馐 馑 馒 馓 馔 馕 首 馗 馘")."<BR>"; echo strlen("Ɛ Ƒ ƒ Ɠ Ɣ ƕ Ɩ Ɨ Ƙ")."<BR>"; Outputs 35 26 A: I am no PHP expert but it seems that strlen it counts bytes... there is mb_strlen which counts characters... EDIT - for further reference on how multi-byte encoding works see http://en.wikipedia.org/wiki/Variable-width_encoding and esp. UTF8 see http://en.wikipedia.org/wiki/UTF-8 and A: It looks like it's counting the number of bytes in the encoding being used. For example, it looks like the second string is taking two bytes per non-space character, whereas the first string is taking three bytes per non-space character. I would expect: echo strlen("A B C D E F G H I") to print out 17 - a single byte per ASCII character. My guess it that this is all using the UTF-8 encoding - which would certainly be in-line with the varying width of representation. A: The first batch of characters take up three bytes each, because they're way down in the 39-thousand-ish character list, whereas the second group only take two bytes each, being around 400. (The number of bytes/octets required per character are discussed in the UTF-8 wikipedia article.) strlen counts the number of bytes taken by the string, which gives such odd results in Unicode. A: Use mb_strlen, it count characters in provided encoding, not bytes as strlen A: According to this post on php.net/strlen, PHP interprets all strings passed to strlen as ASCII.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Rails Design Question - "Hot Right Now" I have multiple models on my site. There are Suggestions and Items as well as Deals. I created a template which shows what is hot right now. I want to be able to apply this to all 3 models mentioned above and was wondering the best way to approach it. Obviously, I can add "hotness_score" on each of this model, and then run cron to update their hotness score every hour (by my own algorithm). However, the inconvenient thing about that is if I want to display the top ten hottest THINGS on my site, I might potentially have to take the top ten hottest object from each of these and then sort them in memory. (Even though I can cache them it doesn't sound really pleasant). I have also thought about creating a new model, aka Hotness, which has the following attributes: * *Type *object_id *hotness_score *last_updated The good thing about this is that I only have to query for Hotness order_by 'hotness_score DESC'.limit(10) and I can get the top 10 of everything combined. Do you think this is a good implementation? Do you see any problems with this? Can someone shed some insights to a better approach to this problem? I welcome all suggestions. A: Yes, I think what you're talking about is a polymorphic model. It's a pretty standard way to do this in Rails: create_table :hot_things do |t| t.column :item, :polymorphic => true # item_id, item_type t.column :score t.timestamps end class HotThing < ActiveRecord::Base belongs_to :item, :polymorphic => true end Something like that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling different screen resolutions in blackberry with single image I have one PNG image and am applying it to all the screens as background. Its resolution is 360x480 because I started programming for 9800 simulator. I am developing for OS 6.0. When I test my app for 9700 simulator having screen resolution 480x360, the image covers only half the screen. I have researched and learnt about using Fixed32 and scale and I have applied it as well. But still the background seems to cause an issue. I have only one image in resource folder. How to handle this one image to apply suitably for all different blackberry devices A: You have to resize the image based to screen width and height to fit to the screen you are are running. For this the following methods will use. public static EncodedImage sizeImage(EncodedImage image, int width, int height) { EncodedImage result = null; int currentWidthFixed32 = Fixed32.toFP(image.getWidth()); int currentHeightFixed32 = Fixed32.toFP(image.getHeight()); int requiredWidthFixed32 = Fixed32.toFP(width); int requiredHeightFixed32 = Fixed32.toFP(height); int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32); int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32); result = image.scaleImage32(scaleXFixed32, scaleYFixed32); return result; } After resizeing use below method for cropping. public static Bitmap cropBitmap(Bitmap original, int width, int height) { Bitmap bmp = new Bitmap(width, height); int x = (original.getWidth() / 2) - (width / 2); // Center the new size by width int y = (original.getHeight() / 2) - (height / 2); // Center the new size by height int[] argb = new int[width * height]; original.getARGB(argb, 0, width, x, y, width, height); bmp.setARGB(argb, 0, width, 0, 0, width, height); return bmp; Create bitmap image as follow. EncodedImage eImage = EncodedImage.getEncodedImageResource("img/new.png" ); EncodedImage bitimage=sizeImage(eImage,Display.getWidth(),Display.getHeight()); Bitmap image=cropBitmap(bitimage.getBitmap(),Display.getWidth(),Display.getHeight()); pass above bitmap to you manager. Now set the returned bitmap as background to screen.It worked for me.Hope this will help to you. A: To set your image with required width and height use Bitmap scale; And if you want to put your image as Background then put the bitmap image to VerticalFieldManager like this: For all devices it works: Bitmap bit=Bitmap.getBitmapResource("background.png"); Bitmap scalingBitmap=new Bitmap(Device.getWidth(),Device.getHeight()); //here you can give any size.Then it sets the image according to your required width and height; bit.scaleInto(scalingBitmap, Bitmap.FILTER_LANCZOS); //This is important; VerticalFieldManager mainVertical=new VerticalFieldManager() { //Here Device.getWidth() and Device.getHeight(); These two are your Blackberry Device width and height;(According your 9800 it takes 480x360) protected void paint(Graphics g) { g.clear(); g.drawBitmap(0, 0, Device.getWidth(),Device.getHeight(), scalingBitmap, 0, 0); super.paint(g); } protected void sublayout(int maxWidth, int maxHeight) { super.sublayout(Device.getWidth(),Device.getHeight()); setExtent(Device.getWidth(),Device.getHeight()); } }; add(mainVertical); This is enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET / SQL Server - Timeout expired while searching We have a table called Purchases: | PRSNumber | ... | ... | ProjectCode | | PRJCD-00001 | | | PRJCD | | PRJCD-00002 | | | PRJCD | | PRJCD-00003 | | | PRJCD | | PRJX2-00003 | | | PRJX2 | | PRJX2-00003 | | | PRJX2 | Note: ProjectCode is the prefix of PRSNumber. Before, when there is no ProjectCode field in the table, our former developers use this query to search for purchases with specific supplier: select * from Purchases where left(PRSNumber,5) = @ProjectCode Yes, they concatenate the PRSNumber in order to obtain and compare the ProjectCode. Although, the code above works fine regardless of the table design. But when I added a new field, the ProjectCode, and use this query: select * from Purchases where ProjectCode = @ProjectCode I receive this exception: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. I can't believe, that the first query, which needs concatenation before the compare, is faster than the second one which has to do nothing but compare. Can you please tell me why is this happening? Some information which might be helpful: * *PRSNumber is varchar(11) and is the primary key *ProjectCode is nvarchar(10) *Both query works fine in SQL Server Management Studio *First query works in ASP.NET website, but the second does not *ProjectCode is indexed *The table has 32k rows Update * *ProjectCode is now indexed, still no luck A: First thing I would do is check the index on PRSNumber, I assume there is an index on that field and the table is very large. Adding an index to your new field will likely fix the problem (if that is the case). The code to add an index: CREATE INDEX IX_Purchases_ProjectCode ON dbo.Purchases (ProjectCode); Update: I would also try adding the field as a varchar to eliminate the datatype change from the equation. A: I set the CommandTimeout property of my SqlCommand higher instead of making the query faster. It didn't solve the speed but solved the timeout issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eliminating Initial keypress delay When you type into a textbox and hold a key, you get (a.......aaaaaaaaaaaaaaa), depending on the initial key press delay. addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { // Handle key press here } I'm creating a game in which the user's reflexes are very important. How can I eliminate this delay completely? The above code does not work. I have also tried overriding processKeyEvent with no luck. A: These events are generated by the JVM / operating system, and unless you instruct the user to change the key-delay / key-repeat settings I'm afraid you'll have to do some more work. I suggest you create a Timer which fires events in the correct rate, start and stop the timer upon keyPressed / keyReleased.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Couchdb and Sofa Help I'm new to Couchdb just a few week back I git clone the couchdb app called sofa [what and app] . Over the week It was going great but suddenly today I stumble upon something. Here what I meant when I browse the Sofa app and try to create a Post without the title it prompt with and alert box "The document could not be saved: The database could not be created, the file already exists." which was weird as looking at the source I found that the require (in validate_doc_update.js return its custom json error) something like in this format {"forbidden" : message }) with forbidden as key v.forbidden = function(message) { throw({forbidden : message}) }; v.require = function() { for (var i=0; i < arguments.length; i++) { var field = arguments[i]; message = "The '"+field+"' field is required."; if (typeof newDoc[field] == "undefined") v.forbidden(message); }; }; in validate_doc_update.js if (newDoc.type == 'post') { if (!v.isAuthor()) { v.unauthorized("Only authors may edit posts."); } v.require("created_at", "author", "body", "format", "title"); inspecting the response state that the json returned was found to be different from the json had it would have been return by the above require function in validate_doc_update.js here is the json {"error":"file_exists","reason":"The database could not be created, the file already exists."} This make be believe that the validation in validation_doc_update.js only execute during updating of document to Prove this point I try to update a document without the title, expecting that it would return the error but surprisingly the document just got saved so Here are my Question regarding all the Point I mention above Does validate_doc_update.js "validate" work only during updation of document if YES then how can I manage to succeed in updating a post without the error [Weird bypassing the Validation Completely] . + How can execute validation on create of a document if NO then What is the Error {"error":"file_exists","reason":"The database could not be created, the file already exists."} that is prevent a document to be saved Can anyone please share light on all the questions listed here A: Yes, the validate_doc_update functions are run only when updating documents (include creation and deletion). The function you show here will allow a document without a title as long as its type is not "post". If you could include the actual request you attempted, I could confirm it. Finally, the ""The database could not be created" is because you are attempting to create the database (by doing PUT /dbname/ instead of PUT /dbname/docid, I would guess) when it already exists. Again, if you would include the actual request, I could confirm that too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent a looping script from stopping when aborting the page? I've built a looping script that i want to keep it running in the background. The issue is that when i run it via the browser, it works fine but once i stop loading the page, the script stops/exists, i know that's pretty normal and makes sense, but how can i run a specific PHP script endlessly in the background? It would be great if there is function in php that runs an other script but it goes on instead of waiting for it. A: You are probably looking for: * *shell_exec(..) *exec(..) *escapeshellcmd(../=) A: It is possible to run your script from command line as a process in background. Look here Run php script as daemon process or look at http://pear.php.net/package/System_Daemon that could help you to make it work :) Web server kills your script because when user going on another site, server needs to spawn new PHP process for example and close older one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a Round Edged form in C# private static extern IntPtr CreateRoundRectRgn ( int nLeftRect, // x-coordinate of upper-left corner int nTopRect, // y-coordinate of upper-left corner int nRightRect, // x-coordinate of lower-right corner int nBottomRect, // y-coordinate of lower-right corner int nWidthEllipse, // height of ellipse int nHeightEllipse // width of ellipse ); public Form1() { InitializeComponent(); Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0,Width-5, Height - 5, 20, 20)); } Ive got this Code from Stack Overflow but, this does not produce a clear edged window and moreover the minimize, maximize buttons are not displayed properly. Please Correct the Code. Is there any library(dll) to do the job in C#. A: You can find interesting discussion here http://bytes.com/topic/c-sharp/answers/256570-how-do-i-create-windows-forms-rounded-corners. Or if you have not sizable forms you can use an easy trick like here http://msdn.microsoft.com/en-us/beginner/cc963986.aspx. But doing It well in WindowsForms is really hard. So if it can be an option to you, I would strongly suggest to use WPF instead. Especially I see you concern about not perfect rendering.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can each row in an HTML table be numbered? What I would like to do is number each row in my table. I can't manually number the table myself, as all of the info in it is retrieved from a database. Is this possible with jQuery or PHP? Here's a screen shot of the table: I tried searching for this, and did not find anything that helped me. Here is the PHP / HTML that is displaying the table: <tr> <th>Name</th> <th>Email</th> <th>Subject</th> <th>Created on</th> <th style="width:65px;">Status</th> <th>Actions</th> </tr> <?php [...] //Display the results while($info = mysql_fetch_assoc($result)){ //data $name = $info['name']; $email = $info['email']; $subject = $info['subject']; $ticketid = $info['ticket']; $isActive = $info['is_active']; $created = $info['created']; //status if($isActive == "1") { $status = "<span class=\"open\">Open</span>"; $status2 = "active"; } else if($isActive == "0") { $status = "<span class=\"closed\">Closed</span>"; $status2 = "closed"; } else { $status = ""; } echo " <tr> <td style=\"min-width: 87px;\">$name</td> <td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td> <td title=\"$subject\">".addEllipsis($subject, 18)."</td> <td style=\"width: 235px;\">$created</td> <td title=\"This ticket is $status2\">$status</td> <td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket &raquo;</a></td> </tr> "; } As you can see, it's displayed with a while loop. If anyone knows a way to number each line in my table with jQuery or PHP, please help me :) A: $trCounter=0; while($info = mysql_fetch_assoc($result)){ //data $name = $info['name']; $email = $info['email']; $subject = $info['subject']; $ticketid = $info['ticket']; $isActive = $info['is_active']; $created = $info['created']; //status if($isActive == "1") { $status = "<span class=\"open\">Open</span>"; $status2 = "active"; } else if($isActive == "0") { $status = "<span class=\"closed\">Closed</span>"; $status2 = "closed"; } else { $status = ""; } echo " <tr> <td>$trCounter++</td> <td style=\"min-width: 87px;\">$name</td> <td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td> <td title=\"$subject\">".addEllipsis($subject, 18)."</td> <td style=\"width: 235px;\">$created</td> <td title=\"This ticket is $status2\">$status</td> <td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket &raquo;</a></td> </tr> "; } or you could always use the :eq api in your jquery selector or its equivalent to work with the index but like I asked it depends on what you want to do with the index. A: jQuery: $(function () { var i = 0; $('table thead tr').prepend('<th>#</th>'); $('table tbody tr').each(function () { i += 1; $(this).prepend('<td>' + i + '</td>'); }); }); A: PHP <tr> <th>Sr. No</th> // Add header for counter <th>Name</th> ... </tr> ... $i=1; // add counter -----------corrected------------- while($info = mysql_fetch_assoc($result)){ //data ... echo " <tr> <td>$i</td> // include counter to table <td style=\"min-width: 87px;\">$name</td> ... </tr> "; $i++; // increment counter } A: I would go with PHP solution listed by Atul Gupta. To add more - you also can to start iteration based on which page you are. <?php $i = ($page-1) * $itemsPerPage; while(....) { echo $i; $i++; } ?> if you are on the second page of your list would get something like 11,12,13,14,.... A: Set an auto increment property in the SQL table, which can be used as an index, and will increase automatically when a new entry is added?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to keep data available for whole project access? Well. I have done a small project. But the problem is some of my required data is not available across whole project. I mean, every time I go form to form I need to open the database and fill the same data from the same SqlDataAdapter. Instead is it possible to keep the data somewhere globally for all the project forms? With my project I have a class for the queries and tables and wherever I need data in the forms, there I use to call the Subs for filling the table like the below... Class1.cs ========= public void MyTableFill() { Con.ConnectionString = Con_1; Con.Open(); SQLDAp = new SqlDataAdapter(MyQry, Con); SQLDAp.Fill(MyTable); Con.Close(); } Form1.cs ======== Class1 MyDatas = new Class1(); Form1_Load() { MyDatas.MyTableFill(); } Form2.cs ======== Class1 AccDatas=new Class1(); Form2_Load() { AccDatas.MyTableFill(); } Thanks A: All you need to to is a) in your opening form initialize and fill the adapter b) make a constructor that accepts the adapter in all other forms c) pass the adapter from one form to the next as a argument PS: You may also pass the adapter as a reference, that way any changes are saved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I play multiple songs stored in my raw folder using MediaPlayer in android? How do I play multiple songs that I have stored in a raw folder using MediaPlayer using seek and previous? Thanks. A: To play a file from your Android project's raw folder: MediaPlayer mediaPlayer = MediaPlayer.create(yourActivity, R.raw.filename); mediaPlayer.setLooping(false); mediaPlayer.start(); mediaPlayer.release(); If you have multiple files and want to use next/previous, just create an ArrayList< Object > with your files and write something to select the files from that list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Place the image at random x,y of the screen and make the image invisible after certain peroid in android I need to create an image at random places. After few seconds it has to be disappeared. After the first image get disappeared the second image has to come. I used the following code to place the image at random coordinates and use a handler to make it invisible after few seconds. I used for loop to create some number of images. All the images comes and goes at the same time. I think the for loop is the problem. I couldn't find a solution for that. Any help is appreciated. ImageView iv=null; RelativeLayout rl=null; Random rand= new Random(); int min=10, max=100; int randomNum; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); rl = (RelativeLayout) findViewById(R.id.my_relative_layout); for(int i=0;i<100;i++){ randomNum = rand.nextInt(max - min + 1) + min; Log.d("RandomNum",Integer.toString(randomNum)); Log.d("i value",Integer.toString(i)); iv = new ImageView(this); iv.setBackgroundColor(Color.YELLOW); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40); params.leftMargin = 50+randomNum; params.topMargin = 60+randomNum; rl.addView(iv, params); timerDelayRemoveView(500, iv); } } public void timerDelayRemoveView(long time, final ImageView iv){ Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { iv.setVisibility(View.GONE); } }, time); } A: You can try to implement a timerDelayAddView (like you delayed timerDelayRemoveView) where you specify an image-dependent delay (e.g. 2000 * i) before you call addView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to redirect form a controller and get value in jsp http://localhost:8080/LACASServer/message.jsp?forgotUser=Mail+has+been+sent+to+your+mail+address Here forgotUser is key of a map, that i set in a controller's method, which redirect to message.jsp, now how can i use it this map in message.jap to show value of that map. I am using jstl library controler method is as: @RequestMapping(value = "/forgotPWD",params="username", method = RequestMethod.POST) public String forgotPassword(@RequestParam(value = "username", required = false) String username,Map<String, Object> map) { System.out.println("forgotPasswordUser"+username); ResetPasswordLog resetPasswordLog; User forgotPasswordUser = usersService.findUser(username); map.put("forgotUser","Mail has been sent to your mail address"); if(forgotPasswordUser==null){ return "redirect:/login.jsp?login_error=1"; } else { Integer uid=forgotPasswordUser.getId(); resetPasswordLog= usersService.setTempHash(uid); String TEMPHASH= resetPasswordLog.getTempHash(); String url=Utility.serverURL+"forgot/index?uid="+uid+"&token="+TEMPHASH; System.out.println(url); System.out.println(Utility.mailResetSubject); mailSender.sendMail(Utility.mailFrom,"romijain3186@gmail.com",Utility.mailResetSubject, url); return "redirect:/message.jsp"; } } A: You need your controller method (the one shown above) to specify the "view" itself (not use a redirect, as it currently does). So the return value should be a String that corresponds to the view name for message.jsp. You can then add the map to the model and it will be available in the JSP. E.g. @RequestMapping(value = "/forgotPWD",params="username", method = RequestMethod.POST) public String forgotPassword(@RequestParam(value = "username", required = false) String username, Map<String, Object> map, Model model) { [snip] map.put("forgotUser","Mail has been sent to your mail address"); model.addAttribute("userMap", map); [snip] return "message.jsp"; // or just "message" depending on Spring settings } Then in your JSP access the map via JSTL: ${userMap.forgotUser}
{ "language": "en", "url": "https://stackoverflow.com/questions/7537599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSString/NSMutableString strange behaviour OK here is nsmutablestring data = [NSMutableString stringWithFormat:@"&cb_games%5B%5D="]; Now when ever I try to print or use this string I get big number instead of %5B and %5D not sure why this is happeing any help would be apritiated thanks A: The reason you get unexpected output is that '%' is used as conversion specifier in printf and obviously NSLog and NSString formattings. You need to escape '%' if you don't want it to be interpreted as a conversion specifier. You can escape '%' by preceding it with another '%' like '%%'. Your string should look like, @"&cb_games%%5B%%5D=" And the @August Lilleaas's answer is also noteworthy. A: Try this: NSString * data = [NSMutableString stringWithFormat:@"&cb_games%%5B%%5D="]; NSLog(@"%@",data); A: stringWithFormat is basically printf, and it attempts to replace your percentages with values that you haven't provided, which is why wierd stuff happens. [NSMutableString stringWithFormat:@"Hello: %d", 123]; // @"Hello: 123" If you want a mutable string from a string, try this: [NSMutableString stringWithString:@"Abc %2 %3"]; // @"Abc %2 %3" A: The % is used for string formatting and stuff. I imagine you need to escape the character or something, possibly with a slash. A: Did you mean to write? data = [NSMutableString stringWithString@"&cb_games%5B%5D="]
{ "language": "en", "url": "https://stackoverflow.com/questions/7537602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add navigation links in c# windows application I want to create a form with 2 panels in which the left panel contains links. When a link is clicked, the corresponding form should open up in the right area and should refresh when another link is clicked and should show that form. I want to do this in c# windows application. How do I do it? A: As @AVD suggests for link you should use LinkLabel but in order to open forms in 'right' or anyother specified panel, you have to set the Parent handle of Forms to the handle of containing Panel. So lets say you have two panels, splitContainer1.LeftPanel and splitContainer1.RightPanel. In left Panel you have LinkLabel with LinkClicked event. Now in order to open a Form in splitContainer1.RightPanel when LinkLabel is clicked, instantiate an object of Form, call the Win API method SetParent() to set the parent handle and then call the Form.Show() method to open it in splitContainer1.RightPanel //Declare a WinAPI method [DllImport("user32.dll", SetLastError = true)] static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //Inside LinkClicked event private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Form1 f = new Form1(); SetParent(f.Handle, splitContainer1.Panel2.Handle); f.Show(); } Edit: A workaround to close any existing form in panel before opening a new Not the best but easiest way to close existing form: Form currentForm = null; private void CloseCurrentForm() { if(currentForm != null) currentForm.Close(); } and in every LinkClicked event call this method before opening a new Form like this, don't forget to set the currentForm: private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { CloseCurrentForm(); Form2 f = new Form2(); SetParent(f.Handle, splitContainer1.Panel2.Handle); currentForm = f; f.Show(); } A: For your problems, you can use Panel controls. and User Controls. First create UserControl, Then you can add it to the panel container. UserControls help to re usability, and will be easier to re use it. Steps to do * *Create a user control and design it accoriding to your need *Put a panel Control *Load the Usercontrol object in Panel and display it For Eg . U put one Link Label or Image or Button in your Left Side of Form, and in right side the content Panel . when u clicked LinkLabel do the following Protected void LinkLabel_Click() { UserControl1 UserObj =new UserControl1(); // UserControl which u want to display panel1.controls.Clear(); Panel1.Controls.Add(userobj); //Adding the control to Panel Container. } A: You should use LinkLabel control and create MDI to open/show child forms. A: Have you tried to use the Custom Properties used in c# to open new forms, try it here. Use the Link button. A: I think you searching for http://msdn.microsoft.com/en-us/library/system.windows.forms.linklabel.aspx . LinkLabel control. Handle its LinkClicked event and do what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hole punching over http How can I do the hole punching over http,like I have a server in godaddy Its port access for tcp listeners is closed,so can I get the client's port number from its request to an aspx page? A: If you are using java and have access to the http request on the server side, you can get the remote address and port with the getRemoteAddr() and getRemotePort() methods in the servlet handling the request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to programmatically dim Mac backlit keyboard Is there a way to programmatically dim a backlit keyboard on a Mac? A: UInt64 lightInsideGetLEDBrightness() { kern_return_t kr = 0; IOItemCount scalarInputCount = 1; IOItemCount scalarOutputCount = 1; UInt64 in_unknown = 0, out_brightness; //kr = IOConnectMethodScalarIScalarO(dataPort, kGetLEDBrightnessID, // scalarInputCount, scalarOutputCount, in_unknown, &out_brightness); kr = IOConnectCallScalarMethod(dataPort, kGetLEDBrightnessID, &in_unknown, scalarInputCount, &out_brightness, &scalarOutputCount); return out_brightness; } It may help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Conditional injection of bean I want to have inject a bean based on a String parameter passed from client. public interface Report { generateFile(); } public class ExcelReport extends Report { //implementation for generateFile } public class CSVReport extends Report { //implementation for generateFile } class MyController{ Report report; public HttpResponse getReport() { } } I want report instance to be injected based on the parameter passed. Any help would be greatly appretiated. Thanks in advance A: Use Factory method pattern: public enum ReportType {EXCEL, CSV}; @Service public class ReportFactory { @Resource private ExcelReport excelReport; @Resource private CSVReport csvReport public Report forType(ReportType type) { switch(type) { case EXCEL: return excelReport; case CSV: return csvReport; default: throw new IllegalArgumentException(type); } } } The report type enum can be created by Spring when you call your controller with ?type=CSV: class MyController{ @Resource private ReportFactory reportFactory; public HttpResponse getReport(@RequestParam("type") ReportType type){ reportFactory.forType(type); } } However ReportFactory is pretty clumsy and requires modification every time you add new report type. If the report types list if fixed it is fine. But if you plan to add more and more types, this is a more robust implementation: public interface Report { void generateFile(); boolean supports(ReportType type); } public class ExcelReport extends Report { publiv boolean support(ReportType type) { return type == ReportType.EXCEL; } //... } @Service public class ReportFactory { @Resource private List<Report> reports; public Report forType(ReportType type) { for(Report report: reports) { if(report.supports(type)) { return report; } } throw new IllegalArgumentException("Unsupported type: " + type); } } With this implementation adding new report type is as simple as adding new bean implementing Report and a new ReportType enum value. You could get away without the enum and using strings (maybe even bean names), however I found strongly typing beneficial. Last thought: Report name is a bit unfortunate. Report class represents (stateless?) encapsulation of some logic (Strategy pattern), whereas the name suggests it encapsulates value (data). I would suggest ReportGenerator or such.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Get/set data from/to input field in assets HTML file? A WebView loads HTML page from the /assets dir. When a user enters some data into a text field in that HTML file, can my WebView catch/save that data once a user preses some button or link? Also, when a user returns to that page, can I fill the text field with the data he previously entered? I am trying to create a way to save temporary data between HTML pages in /assets dir.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom look svg GUI widgets in QT, very bad performance So I'm trying to make a gui for a guitar effects program. One goal is to allow others to design svg "skins" to customize the look. I made widgets that inherited each widget (i.e. qdial) and in the initializer load the svg file specified by the skin into a qGraphicsSvgItem. This is put into a scene and a view and I overloaded the resize and repaint appropriately. This works. When I load several of these custom svg widgets (5 dials, a button, and an led) into a parent widget the cpu rails and my program freezes. Am I going about this entirely the wrong way? Should I even be using QT? It seemed easier than trying to do everything with a stylesheet (especially I couldn't figure out how to change the dial appearance). Would it improve things to leave the widgets as qGraphicsSvgItems and put them all into the parent widget's scene and view? This is meant to be a real time signal processing program so I don't want to burn up a lot of cpu in the GUI. I tried to do some research on it but couldn't find a lot for svg. I also don't see any performance checker in qtCreator or I'd try to see what the bottleneck is. Anyway I'd really appreciate any advice you could offer before I spend more time trying to do something the wrong way. Thanks so much! _ssj71 p.s. Here is some of the code (hopefully enough) an svg widget: #ifndef QSVGDIAL_H #define QSVGDIAL_H #include <QWidget> #include <QDial> #include <QtSvg/QSvgRenderer> #include <QtSvg/QGraphicsSvgItem> #include <QGraphicsView> #include <QGraphicsScene> class qSVGDial : public QDial { Q_OBJECT public: explicit qSVGDial(QWidget *parent = 0); explicit qSVGDial(QString knobFile = "defaultKnob.svg", QString needleFile = "defaultNeedle.svg", QWidget *parent = 0); ~qSVGDial(); private: void paintEvent(QPaintEvent *pe); void resizeEvent(QResizeEvent *re); float degPerPos; float middle; float mysize; QGraphicsView view; QGraphicsScene scene; QGraphicsSvgItem *knob; QGraphicsSvgItem *needle; QSize k,n; }; #endif // QSVGDIAL_H the cpp: #include "qsvgdial.h" #include "math.h" qSVGDial::qSVGDial(QWidget *parent) : QDial(parent) { knob = new QGraphicsSvgItem("defaultKnob.svg"); needle = new QGraphicsSvgItem("defaultNeedle.svg"); view.setStyleSheet("background: transparent; border: none"); k = knob->renderer()->defaultSize(); n = needle->renderer()->defaultSize(); needle->setTransformOriginPoint(n.width()/2,n.height()/2); knob->setTransformOriginPoint(k.width()/2,k.height()/2); degPerPos = 340/(this->maximum() - this->minimum()); middle = (this->maximum() - this->minimum())/2; mysize = k.width(); if (mysize<n.width()) mysize = n.width(); if (mysize<k.height()) mysize = k.height(); if (mysize<n.height()) mysize = n.height(); mysize = sqrt(2)*mysize; view.setDisabled(true); view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scene.addItem(knob); scene.addItem(needle); view.setScene(&scene); view.setParent(this,Qt::FramelessWindowHint); } qSVGDial::qSVGDial(QString knobFile, QString needleFile, QWidget *parent) : QDial(parent) { knob = new QGraphicsSvgItem(knobFile); needle = new QGraphicsSvgItem(needleFile); view.setStyleSheet("background: transparent; border: none"); k = knob->renderer()->defaultSize(); n = needle->renderer()->defaultSize(); needle->setTransformOriginPoint(n.width()/2,n.height()/2); knob->setTransformOriginPoint(k.width()/2,k.height()/2); if (k!=n) needle->setPos((k.width()-n.width())/2,(k.height()-n.height())/2); degPerPos = 340/(this->maximum() - this->minimum()); middle = (this->maximum() - this->minimum())/2; mysize = k.width(); if (mysize<n.width()) mysize = n.width(); if (mysize<k.height()) mysize = k.height(); if (mysize<n.height()) mysize = n.height(); mysize = sqrt(2)*mysize; view.setDisabled(true); view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scene.addItem(knob); scene.addItem(needle); view.setScene(&scene); view.setParent(this,Qt::FramelessWindowHint); } qSVGDial::~qSVGDial() { //delete ui; } void qSVGDial::paintEvent(QPaintEvent *pe) { needle->setRotation((this->sliderPosition() - middle)*degPerPos); } void qSVGDial::resizeEvent(QResizeEvent *re) { if (this->width()>this->height()) { view.setFixedSize(this->height(),this->height()); view.move((this->width()-this->height())/2,0); knob->setScale(this->height()/mysize); needle->setScale(this->height()/mysize); view.centerOn(knob); } else { view.setFixedSize(this->width(),this->width()); view.move(0,(this->height()-this->width())/2); knob->setScale(this->width()/mysize); needle->setScale(this->width()/mysize); view.centerOn(knob); } QDial::resizeEvent(re); } The parent header: #ifndef PEDAL_H #define PEDAL_H #include <QtGui/QWidget> #include <QString> #include <QtSvg/QSvgRenderer> #include <QtSvg/QGraphicsSvgItem> #include <QGraphicsView> #include <QGraphicsScene> #include <skin.h> #include <qsvgdial.h> #include <qsvgbutton.h> #include <qsvgled.h> #include <qsvgslider.h> class Pedal : public QWidget { Q_OBJECT public: explicit Pedal(QWidget *parent = 0); explicit Pedal(QString boxFile, QWidget *parent = 0); ~Pedal(); int LoadSkin(skin skinfiles); QWidget* AddControl(QString type, QString param, int x, int y, int w, int h, QString file1, QString file2, QString file3, QString file4); private: void resizeEvent(QResizeEvent *re); QRect PedalPosition(); float myheight; float mywidth; float scale; int effectNumber; QGraphicsView view; QGraphicsScene scene; QGraphicsSvgItem *box; QSize p; QWidget* controls[20]; QRect ctrlPos[20]; int numControls; }; #endif // PEDAL_H parent cpp #include "pedal.h" #include "math.h" Pedal::Pedal(QWidget *parent) : QWidget(parent) { numControls = 0; box = new QGraphicsSvgItem("stompbox.svg"); view.setStyleSheet("background: transparent; border: none"); p = box->renderer()->defaultSize(); box->setTransformOriginPoint(p.width()/2,p.height()/2); myheight = p.height(); mywidth = p.width(); view.setDisabled(true); view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scene.addItem(box); view.setScene(&scene); view.setParent(this,Qt::FramelessWindowHint); } Pedal::Pedal(QString boxFile, QWidget *parent) : QWidget(parent) { numControls = 0; box = new QGraphicsSvgItem(boxFile); view.setStyleSheet("background: transparent; border: none"); p = box->renderer()->defaultSize(); box->setTransformOriginPoint(p.width()/2,p.height()/2); myheight = p.height(); mywidth = p.width(); view.setDisabled(true); view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scene.addItem(box); view.setScene(&scene); view.setParent(this,Qt::FramelessWindowHint); } Pedal::~Pedal() { } void Pedal::resizeEvent(QResizeEvent *re) { view.setFixedSize(this->width(),this->height()); //view.move((this->width()-this->height())/2,(this->width()-this->height())/2); if (this->width()/mywidth>this->height()/myheight) { scale = this->height()/myheight; } else { scale = this->width()/mywidth; } box->setScale(scale); view.centerOn(box); //QWidget::resizeEvent(re); QRect v = PedalPosition(); QRect cpos; for(int i = 0; i<numControls; i++) { cpos = ctrlPos[i]; controls[i]->setGeometry(v.x()+cpos.x()*scale,v.y()+cpos.y()*scale,cpos.width()*scale,cpos.height()*scale); } } QWidget* Pedal::AddControl(QString type, QString param, int x, int y, int w, int h, QString file1, QString file2, QString file3, QString file4) { QWidget* control; if (type.toLower() == "dial") { if (!file2.isEmpty()) control = new qSVGDial(file1,file2,this); else control = new qSVGDial(this); } else if (type.toLower() == "button") { if (!file2.isEmpty()) control = new qSVGButton(file1,file2,this); else if (!file1.isEmpty()) control = new qSVGButton(file1,this); else control = new qSVGButton(this); } else if (type.toLower() == "slider") { if (!file2.isEmpty()) control = new qSVGSlider(file1,file2,this); else if (!file1.isEmpty()) control = new qSVGSlider(file1,this); else control = new qSVGSlider(this); } else if (type.toLower() == "led") { if (!file2.isEmpty()) control = new qSVGLED(file1,file2,this); else control = new qSVGLED(this); } control->setToolTip(param); ctrlPos[numControls] = QRect(x,360-y-h,w,h); controls[numControls] = control; numControls++; return control; } QRect Pedal::PedalPosition() { QRect mypos; mypos.setWidth(mywidth*scale); mypos.setHeight(myheight*scale); mypos.setX((this->width()-mypos.width())/2); mypos.setY((this->height()-mypos.height())/2); return mypos; } finally the test main #include <QtGui/QApplication> #include "pedal.h" #include <string.h> int main(int argc, char *argv[]) { QApplication a(argc, argv); Pedal w("skins/default/stompbox.svg",0); w.AddControl("Dial" , "Level", 133, 295, 47, 47, "skins/default/blackKnob.svg", "skins/default/whiteNeedle.svg","",""); w.AddControl("Button", "On", 20, 21, 182, 111, "skins/default/blackButton.svg","","",""); w.AddControl("LED", "On", 106, 328, 11, 11, "skins/default/redLEDOff.svg", "skins/default/redLEDOn.svg","",""); w.AddControl("Dial", "Gain", 44, 295, 47, 47, "skins/default/blackKnob.svg", "skins/default/whiteNeedle.svg","",""); w.AddControl("Dial", "Low", 36, 244, 31, 31, "skins/default/blackKnob.svg", "skins/default/whiteNeedle.svg","",""); w.AddControl("Dial", "Mid", 98, 244, 31, 31, "skins/default/blackKnob.svg", "skins/default/whiteNeedle.svg","",""); w.AddControl("Dial", "High", 160, 244, 31, 31, "skins/default/blackKnob.svg", "skins/default/whiteNeedle.svg","",""); w.show(); return a.exec(); } hopefully this helps. As you can see I have layers of QGraphicsViews each with one widget. I suspect now this might be the worst way to do it so I wonder if anyone has more experience before I move forward in a bad direction. Also after playing some more with it, the problem seems to occur when I have 2 instances of the qSVGDial. If I load other combinations of widgets it works alright. Thanks again everyone! A: void qSVGDial::paintEvent(QPaintEvent *pe) { needle->setRotation((this->sliderPosition() - middle)*degPerPos); } This looks very suspicious to me. Doing anything that could result in a redraw from the paintEvent method is dangerous, could lead to infinite update loops. You should connect the dial's sliderMoved signal to a slot in your class and rotate the needle in that slot, and remove the paintEvent handler altogether. If that doesn't trigger an update, call update() in that slot too, but I don't think this should be necessary. (To check if this is the problem in the first place, try printing something to the console inside the paintEvent handler. If it prints like crazy, that's your problem.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7537632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Validating XML that is a DOM document How do I validate an XML document that I already have in memory as a DOM Document? A: You can use the javax.xml.validation APIs to validate XML in memory. Below is an example of using these APIs with a JAXBSource, to validate a DOM model simply use a DOMSource. package blog.validation; import java.io.File; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.util.JAXBSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; public class Demo { public static void main(String[] args) throws Exception { Customer customer = new Customer(); customer.setName("Jane Doe"); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); JAXBContext jc = JAXBContext.newInstance(Customer.class); JAXBSource source = new JAXBSource(jc, customer); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File("customer.xsd")); Validator validator = schema.newValidator(); validator.setErrorHandler(new MyErrorHandler()); validator.validate(source); } } For More Information * *http://blog.bdoughan.com/2010/11/validate-jaxb-object-model-with-xml.html A: How do you made up your model? I have a solution at work where i get an XML message in text format which i parse using xmlbeans. Then i have the ability to call a validate method on it. So there is a Java class compiled during my maven build which reflects the XSD i have. A: There's nothing special about it. The javax.xml.validation validators take a Source. Check the constructors of the implementing classes of Source.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to avoid stop script error in browsers I have a page of more than 2500 anchor tag to process. Now in IE it is throwing the stop script error. Is it possible to do as a batch? Taking 500 executing it and then take the another 500 executing it?? This is the code... ajaxLinks : function(el, flag) { var links = $(el).find('a'); var notLinkAr=["a[href^=javascript]","#toolbarId ul li>a","#tool_settings .link a",".page-action-links li>a","#tool_settings .label a",".success-map .success-tabs li>a",".success-map .sm_loggedin li>a", ".analyst_cat li>a",".modal",".layer",".newpage",".close",".hideFromPopup",".pagenum",".next",".prev",".delete_src",".tips","#hidr","#backr"]; $(notLinkAr).each(function(index){ var notLinkI=$(notLinkAr[index]); if($(notLinkI).is("a")){ if($(notLinkI).length>0){ $(notLinkI).each(function(index1){ $(notLinkI[index1]).addClass("dontAjaxify"); }); } } }); $(links).each(function(i, obj){ var link = $(obj); if(!$(obj).hasClass('dontAjaxify')){ link.attr('rel', link.attr('href')); var rellnk = link.attr('rel'); if(flag=='ajaxified') { if(/http/.test(rellnk)){ var relurl; relurl=rellnk.replace((window.location.protocol + "//"+ window.location.hostname),'') link.attr('rel', relurl);; } } link.bind('click', function(e){} Iam adding a class for all the anchor tag(which is 2500) in a page. A: jQuery's .slice may help you. http://api.jquery.com/slice/ var count = 0; var ajaxify = function (el, flags) { var links = $(el).find('a').slice(count, count + 500); count = count + 500; // Do the processing here if (links.length) { // Call it next time only if some data is returned in the current call setTimeout("ajaxify()", 5000); } } The above code is not tested, but should probably work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSH smoke & mirrors Situation: I've been given SSH access to a server running LAMP (Redhat) and the brief is to migrate files and database from current live server to this new development server for testing. Further this SSH access is contained within a Protected Workspace, so basically I have to access this companies internal network and then I can access the server there through SSH. Issue: SSH - WTF?? :- In the murky world of media agency smoke and mirrors alas I'm not allowed to admit weakness and it appears that I won't have access to my familiar tools (filezilla + sequelpro) I managed to logon to the server yesterday with Putty though have no idea how to achieve the mission: * *Create a database *Import data to that database *Upload files *Set permission on files and folders *At what address will I be able to view the website? Is there a kind soul out there who can point me in the right direction? Thanks. A: What's the problem with FileZilla? If its available on the server - run it, SSH has nothing to do with that. You'll probably want to have X server running on your computer though, and set up port forwarding in Putty to allow applications running through SSH to connect to it. SSH is what it is: secured shell connection. Once you gained access through SSH you can do everything you could do using local console.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to find if an item in a Windows folder is really hidden from the user? I need to get the count of items (folders and files) in a Windows folder. I can easily do it based on the condition if I should include hidden items or not. But in my program I want to get the count of items that is visible to the user! i.e. if hidden items are visually visible in the folder, then it should be included in the count. If hidden items are not visible, then it shouldnt be included. So how can I know if "show hidden files" property is set on Windows machine. In other words is there a way I can find if a file or directory is "really hidden" (visually) from the user?? Update: I am going to re-open this question. Though the original answers here answered my question, to a certain extent its not foolproof. Here is the new scenario: Certain files in C drive (not anywhere else yet), are visually hidden, though their hidden attribute is false (or unchecked), strangely. Those files look pale like other hidden files when made visible (from folder options) and they get visually hidden when we set "do not show hidden files" in folder options (like any other normal hidden file). Those files in my machine as I see are autoexec.bat and config.sys in C:\. I found this on a Windows XP machine and as well as a Windows 7 machine. Is there a way to identify such files? Basically I was trying to get the count of visible(visually) files in a directory, and my application fails when it attempts to get count of files in C:\. What happens is that the application counts those two files (since its attribute is not hidden), but from a visual standpoint, they are hidden normally, like this: string[] f = Directory.GetFiles(path); int count = 0; foreach (string s in f) { FileInfo i = new FileInfo(s); if ((i.Attributes & FileAttributes.Hidden) == 0) count++; } return count; So I think the only correct way is calling the Shell API. I am looking for a good starter.. Thanks.. A: There is a registry key to check for the global flag regarding "showing hidden files" at Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Hidden - see http://www.pctools.com/guides/registry/detail/1007/ Edit: Beware that there is another setting regarding "show system files" called ShowSuperHidden A: This setting is stored in the registry, it is located: User Key: [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ Advanced] Value Name: Hidden Data Type: REG_DWORD (DWORD Value) Value Data: (1 = show hidden, 2 = do not show) The code to access this value: int hiddenValue = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\","Hidden",2); if(hiddenValue == 1) { //Files not hidden } else { //Files are hidden } Registry Key Details A: autoexec.bat and config.sys in C:\ are system files which mention by Yahia, the ShowSuperHidden setting. Here is how you can check whether the file is system files or not. When the file attributes is HSA, it means Hidden, System & Files ready for archiving. Below are the list for file attributes. File attributes: A = Files ready for archiving H = Hidden C = Compressed HC is two attributes = Hidden & Compressed R = Read-only S = System HSA is three attributes = Hidden, System & Files ready for archiving E = Encrypted Encrypted files and folders cannot be compressed. Sources : http://www.tomshardware.com/forum/115561-45-file-attribute
{ "language": "en", "url": "https://stackoverflow.com/questions/7537647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what could this generic class declaration could mean? I know this isn't a good question to ask and I might get cursed to ask it but I cannot find any place to get help on this question Below is a Generic class that appeared in my interview question (which I have already failed). The question was to tell what this Class declaration is doing and in what circumstances this could be used for ? I have very limited understanding of Generic programming but I understand that 'T' is Type and 'extends' here means that the Type should have inherited 'SimpleGenericClass' but I do not understand the '?' at the end and in what circumstances this Class could be potentially used for public abstract class SimpleGenericClass<T extends SimpleGenericClass<?>> { } A: First, because the class SimpleGenericClass is abstract, it is meant to be subclassed. Second, it is a generic class which means that inside the class somewhere you will almost assuredly be using the generic parameter T as the type of a field. public abstract class SimpleGenericClass<T...> { T x; } Now the first interesting thing here is that T is bounded. Because it is declared as T extends SimpleGenericClass<?> it can only be SimpleGenericClass<?> or some subclass of SimpleGenericClass<?>. You also asked about thr ?. That's known as a wildcard and there is a pretty good explanation of it at the Java Tutorial on Wildcards. In your case we would say this is a "SimpleGenericClass of unknown." It is needed in Java because SimpleGenericClass<Object> is NOT the superclass of SimpleGenericClass<String>, for example. The second interesting thing though is that since T is a SimpleGenericClass of some sort, your class is more than likely defining recursive structures. What comes to my mind are trees (think of expression trees) where SimpleGenericClass is the (abstract) node type, designed to be subclassed with all kinds of specialized node types. UPDATE This SO question on self-bounded generics might be helpful to you. UPDATE 2 I went ahead and put together some code that illustrates how this can be used. The app doesn't do anything but it does compile and it shows you how the generic bounds can supply some possibly-meaningful constraints. public abstract class Node<T extends Node<?>> { public abstract T[] getChildren(); } class NumberNode extends Node { int data; public Node[] getChildren() {return new Node[]{};} } class IdentifierNode extends Node { int data; public Node[] getChildren() {return new Node[]{};} } class PlusNode extends Node { NumberNode left; NumberNode right; public NumberNode[] getChildren() {return new NumberNode[]{};} } The nice thing here is that NumberNode[] is a valid return type for PlusNode.getChildren! Does that matter in practice? No idea, but it is pretty cool. :) It's not the greatest example, but the question was rather open ended ("what might such a thing be used for?"). There are other ways to define trees, of course. A: This really only means that you allow the user of class SimpleGenericClass to parametrize instances of the class with the type T. However, T cannot be any type, but must be a subtype of SampleGenericClass (or SampleGenericClass itself). In the remainder of the code of class SimpleGenericClass you may use type T in method signatures. Let's assume for a second that SimpleGenericClass is not abstract. When using it, you could then write: new SimpleGenericClass<SampleGenericClass<String>>(); I.e. you parametrize SimpleGenericClass with SampleGenericClass and SampleGenericClass with String. A: By definition it says that the SimpleGenericClass can work on a type <T> which is subclass of SimpleGenericClass. So I assume there will be some operations which will work on <T>. Now to see why one would define a template like this - (not much I can think of , really ) may be a scenario where the SimpleGenericClass is an abstract class (just realized it is as per OP :P) and expects that it can work on any concrete classes ? Guys what do you think ? A: This basically sais: in this class you have a Type placeholder called T, and a restriction on that placeholder, it must be of type SimpleGenericClass or something that extends it. Once you obey that rule you can create instances of your class and give an actual type to T, that later on can be used in methods of that class, something like this: public class C <T extends Number>{ public void doSomething(T t) { } public static void main(String... args) { //works: C<Number> c = new C<Number>(); c.doSomething(new Number() { //Aonimous implementation of number }); //won't work //C<Object> c = new C<Object>(); C<Integer> c2 = new C<Integer>(); c2.doSomething(new Integer(1)); //won't work //c2.doSomething(new Number() { //Aonimous implementation of number //}); } } The SimpleGenericClass<?> is pretty redundant at this point. If another generic type is needed on this class, you can have more than one (SimpleGenericClass<T extends SimpleGenericClass, T2 extends Whatever>) A: I guess you have got the question in this form (T instead of ?): public abstract class SimpleGenericClass<T extends SimpleGenericClass<T>> Take a look at this code: abstract class Foo<SubClassOfFoo extends Foo<SubClassOfFoo>> { /** subclasses are forced to return themselves from this method */ public abstract SubClassOfFoo subclassAwareDeepCopy(); } class Bar extends Foo<Bar> { public Bar subclassAwareDeepCopy() { Bar b = new Bar(); // ... return b; } } Bar b = new Bar(); Foo<Bar> f = b; Bar b2 = b.subclassAwareDeepCopy(); Bar b3 = f.subclassAwareDeepCopy(); // no need to cast, return type is Bar The trick going on with Foo<SubClassOfFoo extends Foo<SubClassOfFoo>> is: * *Any subclass of Foo must supply a type argument to Foo. *That type argument must actually be a subclass of Foo. *Subclasses of Foo (like Bar) follow the idiom that the type argument they supply to Foo is themselves. *Foo has a method that returns SubClassOfFoo. Combined with the above idiom, this allows Foo to formulate a contract that says “any subclass of me must implement subclassAwareDeepCopy() and they must declare that it returns that actual subclass“. To say that another way: this idiom allows a superclass (such as an Abstract Factory) to define methods whose argument types and return types are in terms of the subclass type, not the superclass type. The trick is done for example in Enum JDK class: public abstract class Enum<E extends Enum<E>> Refer here for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to have footer always at the bottom of page? My page doesn't contain a lot of information, so footer is displayed somewhere in the middle of the page. How can I have that always at the bottom? A: { potition: absolute; bottom: 0; width: 100%; height: some_height; } A: This isn't a fixed position footer. The footer will be offscreen if the page content is taller than the screen. I think it looks better this way. The body and .ui-page min-height and height are necessary to prevent the footer from jumping up and down during transitions. Works with the latest JQM version as of now, 1.4.0 body, .ui-page { min-height:100% !important; height:auto !important; } .ui-content { margin-bottom:42px; /* HEIGHT OF YOUR FOOTER */ } .ui-footer { position:absolute !important; width:100%; bottom:0; } A: jquery mobile approach - <div data-role="footer" data-position="fixed"> A: [data-role=page]{height: 100% !important; position:relative !important;} [data-role=footer]{bottom:0; position:absolute !important; top: auto !important; width:100%;}
{ "language": "en", "url": "https://stackoverflow.com/questions/7537657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Basic animation unusually slow in non-IE browsers Test page: http://adamhaskell.net/misc/dialogtest.html Tested with: Internet Explorer 9, Firefox 6, Chrome 14 The page contains a stripped-down version of a site I'm working on. It uses a custom Alert function (uppercase A to keep the standard alert available). Essentially it creates a mask element and the alert content element, then fades them in using the opacity style. The animation runs on a setInterval with a time delay of 25ms, over a total of 16 frames. The theoretical animation time, therefore, is 400ms. Results: * *Internet Explorer 9: 397-403ms *Firefox 6: 440-460ms *Chrome 12: 800-900ms And that's just the stripped-down, minimal version of the page. Am I doing something wrong, or is Chrome, the "Internet's fastest browser," the bringer of "the Web, now," actually that crap? A: So, I'll just move this here, since this turned out to be the issue: It's not the animation - the animation ran just fine when I had the external CSS disabled, but it's the browser struggling to render the CSS3 properties (namely border-radius, background-size, and box-shadow in this case) over such a short period of time. Removing these should cause much more normal times to match your expected times. Tested on Firefox 6: * *Before CSS: 400ms average, consistent *After CSS: 600ms+ average, varying Tested on Chrome (no control test): * *After CSS: 500-700ms, varying
{ "language": "en", "url": "https://stackoverflow.com/questions/7537660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Efficient data structure/algorithm for transliteration based word lookup I'm looking for a efficient data structure/algorithm for storing and searching transliteration based word lookup (like google do: http://www.google.com/transliterate/ but I'm not trying to use google transliteration API). Unfortunately, the natural language I'm trying to work on doesn't have any soundex implemented, so I'm on my own. For an open source project currently I'm using plain arrays for storing word list and dynamically generating regular expression (based on user input) to match them. It works fine, but regular expression is too powerful or resource intensive than I need. For example, I'm afraid this solution will drain too much battery if I try to port it to handheld devices, as searching over thousands of words with regular expression is too much costly. There must be a better way to accomplish this for complex languages, how does Pinyin input method work for example? Any suggestion on where to start? Thanks in advance. Edit: If I understand correctly, this is suggested by @Dialecticus- I want to transliterate from Language1, which has 3 characters a,b,c to Language2, which has 6 characters p,q,r,x,y,z. As a result of difference in numbers of characters each language possess and their phones, it is not often possible to define one-to-one mapping. Lets assume phonetically here is our associative arrays/transliteration table: a -> p, q b -> r c -> x, y, z We also have a valid word lists in plain arrays for Language2: ... px qy ... If the user types ac, the possible combinations become px, py, pz, qx, qy, qz after transliteration step 1. In step 2 we have to do another search in valid word list and will have to eliminate everyone of them except px and qy. What I'm doing currently is not that different from the above approach. Instead of making possible combinations using the transliteration table, I'm building a regular expression [pq][xyz] and matching that with my valid word list, which provides the output px and qy. I'm eager to know if there is any better method than that. A: From what I understand, you have an input string S in an alphabet (lets call it A1) and you want to convert it to the string S' which is its equivalent in another alphabet A2. Actually, if I understand correctly, you want to generate a list [S'1,S'2,...,S'n] of output strings which might potentially be equivalent to S. One approach that comes to mind is for each word in the list of valid words in A2 generate a list of strings in A1 that matches the. Using the example in your edit, we have px->ac qy->ac pr->ab (I have added an extra valid word pr for clarity) Now that we know what possible series of input symbols will always map to a valid word, we can use our table to build a Trie. Each node will hold a pointer to a list of valid words in A2 that map to the sequence of symbols in A1 that form the path from the root of the Trie to the current node. Thus for our example, the Trie would look something like this Root (empty) | a | V +---Node (empty)---+ | b | c | | V V Node (px,qy) Node (pr) Starting at the root node, as symbols are consumed transitions are made from the current node to its child marked with the symbol consumed until we have read the entire string. If at any point no transition is defined for that symbol, the entered string does not exist in our trie and thus does not map to a valid word in our target language. Otherwise, at the end of the process, the list of words associated with the current node is the list of valid words the input string maps to. Apart from the initial cost of building the trie (the trie can be shipped pre-built if we never want the list of valid words to change), this takes O(n) on the length of the input to find a list of mapping valid words. Using a Trie also provide the advantage that you can also use it to find the list of all valid words that can be generated by adding more symbols to the end of the input - i.e. a prefix match. For example, if fed with the input symbol 'a', we can use the trie to find all valid words that can begin with 'a' ('px','qr','py'). But doing that is not as fast as finding the exact match. Here's a quick hack at a solution (in Java): import java.util.*; class TrieNode{ // child nodes - size of array depends on your alphabet size, // her we are only using the lowercase English characters 'a'-'z' TrieNode[] next=new TrieNode[26]; List<String> words; public TrieNode(){ words=new ArrayList<String>(); } } class Trie{ private TrieNode root=null; public void addWord(String sourceLanguage, String targetLanguage){ root=add(root,sourceLanguage.toCharArray(),0,targetLanguage); } private static int convertToIndex(char c){ // you need to change this for your alphabet return (c-'a'); } private TrieNode add(TrieNode cur, char[] s, int pos, String targ){ if (cur==null){ cur=new TrieNode(); } if (s.length==pos){ cur.words.add(targ); } else{ cur.next[convertToIndex(s[pos])]=add(cur.next[convertToIndex(s[pos])],s,pos+1,targ); } return cur; } public List<String> findMatches(String text){ return find(root,text.toCharArray(),0); } private List<String> find(TrieNode cur, char[] s, int pos){ if (cur==null) return new ArrayList<String>(); else if (pos==s.length){ return cur.words; } else{ return find(cur.next[convertToIndex(s[pos])],s,pos+1); } } } class MyMiniTransliiterator{ public static void main(String args[]){ Trie t=new Trie(); t.addWord("ac","px"); t.addWord("ac","qy"); t.addWord("ab","pr"); System.out.println(t.findMatches("ac")); // prints [px,qy] System.out.println(t.findMatches("ab")); // prints [pr] System.out.println(t.findMatches("ba")); // prints empty list since this does not match anything } } This is a very simple trie, no compression or speedups and only works on lower case English characters for the input language. But it can be easily modified for other character sets. A: I would build transliterated sentence one symbol at the time, instead of one word at the time. For most languages it is possible to transliterate every symbol independently of other symbols in the word. You can still have exceptions as whole words that have to be transliterated as complete words, but transliteration table of symbols and exceptions will surely be smaller than transliteration table of all existing words. Best structure for transliteration table is some sort of associative array, probably utilizing hash tables. In C++ there's std::unordered_map, and in C# you would use Dictionary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: JQuery: How to filter out "a" elements of an html string? So, I have an HTML string that looks just like this: <div> <div class="venue-tooltip"> Filling station <div> <a class="manage-venue-details" rel="venue-id-10" href="javascript:void(0);">Add filling station info</a> </div> </div> </div> I want to get all the contents without the "a" element, so basically to have something like this: <div> <div class="venue-tooltip"> Filling station <div> </div> </div> </div> The HTML is loaded in a js string and I have tried those variants: $(':not(a)', myHtmlString); $(myHtmlString).not('a'); Both of them return unfiltered HTML. Any ideas? My jQuery version is 1.6.1 and I test the above with Firefox 6 A: You cannot use DOM manipulation functions to change a string. Try using regular expresions: code.replace(/<a( |>).*?<\/a>/gi,""); It's more efficient than convert string in DOM, manipulate and then convert it again in again in a string. A: Both not filters will search only on the first level, and not down the tree, they filter collections and do not process the DOM tree recursively. Assuming that myHtmlString IS a jQuery object (so it's valid context) $(':not(a)', myHtmlString); will return collection of the 2 DOM nodes, contained in the myHhtmlString, as neither of them is an 'a' element $(myHtmlString).not('a'); will also return a collection, but with the original HTML, as it's the only element provided and it's not an 'a' element. The difference between the 2 versions is the context provided in the first line of code, so it filter's the children elements of myHtmlString. If you change div.venue-tooltip to a.venue-tooltip, you will see it filtered in the first version. A: This would work, although it's long winded and I have doubts about it's efficiency- var h = '<div><div class="venue-tooltip">Filling station<div><a class="manage-venue-details" rel="venue-id-10" href="javascript:void(0);">Add filling station info</a></div></div></div>'; $(h).find("a").each(function () { //need to get full outer html for replace to work h = h.replace($(this).clone().wrap('<div></div>').parent().html(),'') }) alert(h); Demo - http://jsfiddle.net/XBjNS/ A: (function($) { $.strRemove = function(theTarget, theString) { return $("<div/>").append( $(theTarget, theString).remove().end() ).html(); }; })(jQuery); var htmlToBeChanged=$("#123").html(); var changedHtml= $.strRemove("a",htmlToBeChanged) console.log(changedHtml); Live Demo A: Try this $(myHtmlString).find('a').remove(); $(myHtmlString).appendTo('body');
{ "language": "en", "url": "https://stackoverflow.com/questions/7537669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Looking for Real Time Solution : Efficient DB interaction On the container one java pplication name as sbs is deployed.On the top of it 3 other java applications are deployed let say A, B, and C. Now Application A, B, and C hits one method name as Sing(id) of application sbs which is used to play a message. sing(id) method of application sbs, hits around 200 times per second and play a message for all. My Problem : DB Table : Play ID : Id of play Count : Total number of request for this play id Last Date Time : last date and time when its played Play ID : 1 Count : Total 66 Last Date Time : 10/8/2011 231145 (something) now update the table Play ID : 1 Count : Total 92 Last Date Time : 10/8/2011 231344 (something) I have to update this table and as i mentioned earlier this field changes 200 times per second.Aim is to know how many times this play id has been played at this time. Ho do i do that ? It is not possible to hit database 200 times per second.So i can hit the datebase in every 4-5 seconds(periodicaly) and update the count status of the play id.How do i do that application wise.Need to increment the count 200 times in every second and store value somewhere and update the database...something like this....whats the best efficient approach.... Let me know if you have any confusion Looking for your valuable inputs. Thanks in advance. A: Well you can hit your db 200 times per second or more, but in your scenario here that's not needed. Instead make a in memory synchronized counter (like a singleton class with an atomic integer), that gets incremented each time the song is played, and then updates the count value in the db every like 30 seconds or something. I've actually done something similar to this, it works great. Just ensure that you have one counter class instance per countable entity (song i guess here), and that incrementing the counter value is thread safe (atomic integer should take care of that) A: There is something rather fishy about the problem as you have stated it: * *If it is acceptable to only update the table every 4 or 5 seconds, then you will inevitably be "missing" updates, and the value of count and last_date_time will be out of date if you queried it. *Worse still (maybe) if your system crashes 4.9 seconds after the last update, then your system will entirely lose a few count ticks. If these anomalies matter, then you've got no choice but to synchronously persist the values of count and last_date_time on each sing(...) request. But if they don't matter, why are keeping this information in the database at all? Why don't you just keep it all in memory and accept that the counts reset when the server crashes and restarts? Or if you need to keep the counts for accounting purposes, why don't you write the "play(id)" events to a special logfile and generate the accounts by an offline scan of the logs. By the way, 200 updates per second is not unreasonable, especially if the table is small and you do some tuning. I can afford 4-5 seconds delay in the updation of records. .... If server crashes where are application is deployed then and we can put some logic ..something like....if count value is zero for the particular play id...fetch the last count from DB and then increment it to one. There is a significant flaw in this approach. In the interval between the last update and the application crashing, there could be zero "plays", or one "play" or many "play"s for any given song. When the application comes back, it simply won't know what those "plays" were ... and it can't know unless they were logged somewhere. We are keeping this information in the database becuase by these records we need to fetch records like how many play id played for this time stamp ( something ). The big question ... which you haven't answered ... is whether it matters if you fail to count some "plays" occasionally. * *If it doesn't matter, then caching and doing an update every few seconds is OK. *If it really does matter, then that solution is unacceptable, because it will lose some plays under certain circumstances. The alternative is (as I said before) is to tune the database; e.g. choose the most appropriate database engine / table types / indexes, and tune the SQL or stored procedure used to do the update. 200 updates per second is not excessively expensive if you tune the database properly. If i come across with the solution in which my performance does not impact much then obeviously not. If that is (really) the case, then just go with the "save every 5 seconds" approach. Or if you want better performance "5 minutes" or "5 hours". Actually don't think you really understand what I'm asking ... because it is NOT obvious (to someone who doesn't understand your business) that it doesn't matter, and performance really shouldn't be relevant to the answer at all. It either matters, or it doesn't. Let me put the question another way: "Would it hurt your business if the counts were inaccurate"?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I ignore words containing substrings using componentsSeparatedByString:? I would like to parse the following string using -componentsSeparatedByString:: CHAPTER 5. RULE OF DECISION CHAPTER 6. GOVERNMENTAL EXEMPTION FROM BOND AND SECURITY REQUIREMENTS CHAPTER 7. LIABILITY OF COURT OFFICERS SUBCHAPTER A. LIABILITY OF OFFICER SUBCHAPTER B. LIABILITY OF ATTORNEY SUBCHAPTER C. SUIT ON OFFICIAL BONDS CHAPTER 8. STATE EXEMPTION FROM CERTAIN FEES: FEES PAID BY OPPOSING PARTY CHAPTER 9. FRIVOLOUS PLEADINGS AND CLAIMS SUBCHAPTER A. GENERAL PROVISIONS SUBCHAPTER B. SIGNING OF PLEADINGS CHAPTER 10. SANCTIONS FOR FRIVOLOUS PLEADINGS AND MOTIONS but when I use CHAPTER as the string to separate by, the SUBCHAPTER elements also get broken up because they contain CHAPTER within them. How can I avoid stopping on the SUBCHAPTER elements when parsing the CHAPTER ones using -componentsSeparatedByString:? A: Try using regular expressions regexKit is perfect for this. That will help you to form the exact pattern you are looking for... NSString *regex = @"^CHAPTER [0-9]"; NSPredicate *valtest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; ret = [valtest evaluateWithObject:yourText]; NSLog("Matches: %@", ret);
{ "language": "en", "url": "https://stackoverflow.com/questions/7537674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Intersection query with Lucene With Zned Lucene, when i search for field1:value1, I have 1000 hits returned. When I search for field2:value2, I have 0 hits returned. And when i search for field1:value1 AND field2:value2, I have 1000 hits returned, but I'd rather like to have 0 hits returned ! Why doesn't it do the intersection of the query ? A: I find myself the solution. Actually it works fine this way using the zend lucene API : $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); $query->addTerm(new Zend_Search_Lucene_Index_Term(value1, field1), true); $query->addTerm(new Zend_Search_Lucene_Index_Term(value2, field2), true); $hits = $index->find($query);
{ "language": "en", "url": "https://stackoverflow.com/questions/7537675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'open' REST framework (.Net) We have a homegrown framework that might be useful to implement REST based webservices. It is a .net c# project, used in a webapplication. What it is used like: inline substitution of template 'tags' with dynamic content. sample tag: {{recentposts window=7 max=10}} What it does: parsing 'tag' to command with (checked) parameters, invoking a handler configured to handle the command and return data, transforming the data with xsl, substitute {{...}} with the result. I have a hunch that this could be reworked to create some form of REST based services, parsing an url to a command with parameters, invoking a handler etc. and writing the result to http response. As an alternative to reworking I'm looking for smth that might be useable instead, out of the box. What are mature (open source) frameworks that could be used? It has to provide a http facade, to do the REST stuff easily, and besides provide an API, a way to bypass this facade, allowing command objects to be created, having all the invocation and transformation done and instead of writing to http response to some stream. A: How about ServiceStack? Quote from the webpage: A modern, code-first, DTO-driven, WCF replacement web services framework encouraging best-practices for creating DRY, high-perfomance, scalable REST web services ...and an "overview" slideshow. A: I use EasyHttp to work with REST base serices, it works easily with JSON and XML services and also supports working with retrieved object as a dynamic object. Very easy to plug and use and you don't have to worry about Http Request/Response anymore. A: I think it may be worth taking a look at OpenRasta https://github.com/openrasta/openrasta-stable/wiki The OpenRasta project is a web framework that les you build web applications as simple as public class Home { public string Get() { return "Hello world"; } } It's really nice to use and easy to get started with
{ "language": "en", "url": "https://stackoverflow.com/questions/7537678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Reformating associative arrays To be more specific I want to turn the following array into an associative one. The original array is indexed like [0],[1],[2],…[n]. The function I used was Set::combine of Cakephp but I couldn't recreate all three levels of the desired associative array. Array ( [0] => Array ( [ACCOUNTS] => Array ( [description] => A ) [HEADERS] => Array ( [description] => B ) [COLUMNS] => Array ( [description] => C [id] => 8 ) ) [1] => Array ( [ACCOUNTS] => Array ( [description] => A1 ) [HEADERS] => Array ( [description] => B1 ) [COLUMNS] => Array ( [description] => C1 [id] => 9 ) ) ) The array I want to end up is the following associative array: Array ( [A] => Array ( [B] => Array ( [C] => 8 ) ) [A1] => Array ( [B1] => Array ( [C1] => 9 ) ) ) I can't recreate all (3) levels of the array above. A: Do you mean like: $newarray = array($first['ACCOUNTS']['description'] => array($first['HEADERS']['description'] => array($first['COLUMNS']['description'] => $first['COLUMNS']['id']))); So if you run the following it gives what you want: $first = array( 'ACCOUNTS' => array('description' => 'A'), 'HEADERS' => array('description' => 'B'), 'COLUMNS' => array('description' => 'C', 'id' => '8')); echo "<pre>"; print_r($first); $newarray = array($first['ACCOUNTS']['description'] => array($first['HEADERS']['description'] => array($first['COLUMNS']['description'] => $first['COLUMNS']['id']))); print_r($newarray); You then end up with: Array ( [ACCOUNTS] => Array ( [description] => A ) [HEADERS] => Array ( [description] => B ) [COLUMNS] => Array ( [description] => C [id] => 8 ) ) Array ( [A] => Array ( [B] => Array ( [C] => 8 ) ) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7537682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call a JavaScript function when text is paste occurs in a text area I would like the text area to call a function when a text is pasted into the text area via mouse clicks. I am not getting it to work the way I wanted using onChange. I am aiming to build something like the Twitter tweet box. A: Use the onPaste event. As far as I've tested it works for Ctrl+V pasting, and right-click>Paste pasting. A: document.getElementById(<id>).onpaste= function() { //do something }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to enable User to surf during ASP.NET DLL upload I am using ASP.NET as the backend for windows phone browser. Sometime I need to make changes on the ASP.NET Pages WHILE users are surfing the website. I want to know how can I provide un-interrupted service to user in such a way they can surf during ASP.NET DLL uploading process: Assume * *say, there are a few ASP.NET (DLL) in production WebServer in such a way that all aspx pages in the one Folder and all DLL(s) in bin-folder. *page(1).aspx , page(1.2).aspx , page(1.n).aspx from DLL(1) and page(2.1).aspx, page(2.2) from DLL(2) *default.aspx from DLL(1) Question What will happen if I upload the updated DLL(2) to the production server and leave DLL(1) as it is : * *Can user call the deafult.aspx? *Will user still be able to call aspx pages from DLL(1) during the uploading process? A: The answer to both the questions is YES A: I am a big fan of Martin Fowler's Blue Green Deployment methodology (link). The idea is simple, have two very similar environments setup (staging & production). You make changes to your code, deploy it on staging, do your testing and then swap staging with production via a simple router configuration. It has worked great for us so far. A: You need Microsoft Web Deployment Tool. Please find more details on below link How to deploy an ASP.NET Application with zero downtime A: Are you hosting within a clustered server environment? If your not, I would be more concerned about a single point of failure rather than interrupting clients briefly during a release. That said, the update process in such an environment is much better if your fearful of disturbing your users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent Android WebView caching data Is it possible to prevent a WebView from caching data in /data/data/???/cache/webViewCache? I've set the following on the WebSettings but the cache folder is still used: webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); webSettings.setAppCacheEnabled(false); I've noticed that the cache files are deleted on application exit or when the application goes into the background but I'd prefer for them not to be created at all. Furthermore I'd like to prevent the use of the webview.db & webviewCache.db found in /data/data/???/database. I currently delete the databases like so: context.deleteDatabase("webview.db"); context.deleteDatabase("webviewCache.db"); This appears to have the desired effect and the files don't appear to be recreated again for use. Is it safe to assume this is the case? A: The notes on this page lead me to believe they don't want you to have fine access to the cache: http://developer.android.com/reference/android/webkit/CacheManager.html As far as I can tell, there are (at least) two ways around keeping cache. I haven't written any of this in an app, so no guarantees: (1) Every time your WebView finishes a page, clear the cache. Something like this in your WebViewClient: @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.clearCache(true); } (2) If you don't care too much what is stored, but just want the latest content, you might be able to achieve this by setting the right http headers on loadUrl (obviously you'd want to test this against your server). Also, this is only available for Android API 8+ Map<String, String> noCacheHeaders = new HashMap<String, String>(2); noCacheHeaders.put("Pragma", "no-cache"); noCacheHeaders.put("Cache-Control", "no-cache"); view.loadUrl(url, noCacheHeaders); Maybe you tried this, but maybe also set the WebView Cache size to something small. I'm not sure if 0 will work, so maybe 1: wv.getSettings().setAppCacheMaxSize(1); Good Luck! A: In my application (on Android 4.2.2) I load on a webview a web page with images that I can change at runtime (I replace the images while keeping the path). The Matt's solution (1) @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.clearCache(true); } works for me, the solution (2) no! Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7537701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: The setOnClickPendingIntent() does not work on existing widgets after device boots up I have a widget which is supposed to react on click/tap events, and it does work perfectly until I reboot the device/emulator. After a reboot, I have to manually remove all the widget instances from the screen and re-add them to make them react on events again. The code below is called both in the onEnabled()- and onUpdate()-methods. And I double checked that all lines of the code is executed in both methods during device startup. public void doSetUpClickIntent( Context context ) { PendingIntent pendingIntent = UtilityClass.doCreateIntent( context ); if ( pendingIntent != null ) { ComponentName componentName = new ComponentName(context, WidgetProvider.class ); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int [] appWidgetIds = appWidgetManager.getAppWidgetIds(componentName); for ( int appWidgetId : appWidgetIds ) { RemoteViews views = new RemoteViews( context.getPackageName(), R.layout.widget ); views.setOnClickPendingIntent( R.id.widgetlayout, pendingIntent ); appWidgetManager.updateAppWidget( appWidgetId, views ); } } } I am at loss to find a cause. What am I doing wrong? Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: keys and values without quotes in an Array? Help me understand this code : Array ( [font-family] => font-family: 'Abel', sans-serif; [font-name] => Abel [css-name] => Abel ) from : http://phat-reaction.com/googlefonts.php . Why there are no quotes around keys and values ? Is this valid php code ? A: Why there are no quotes around keys and values ? It is a dump of some array data in a format designed for a human to read, not code. See print_r. Is this valid php code ? No. A: What you see here is an example of a dump, and not valid PHP. However, to answer your question about the quotations, you can look at the PHP documentation. For the keys, if you look in the PHP documentation, you will see it listed in the don'ts. But, as it says This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that. Values should always be contained in quotes, especially ones with spaces, since they will not be converted correctly using this deprecated format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Recovering git repository from the objects directory I don't know how it happened, but I had a data loss and was only left with a .git directory containing only an objects directory. I've followed the steps from Recovering Git repository from objects only: * *Created a new directory and ran git init *Copied the objects directory I had to the new .git/objects directory *Ran git fsck command. The output of the above steps produced the following msg: notice: HEAD points to an unborn branch (master) notice: No default references dangling commit 0b2c7d52b6a7e6d4e2858e9ebf207c315407c87c dangling commit 8dceafea1634c923069f6d4b925839c28d92c4e5 dangling commit dd7bdd04c557a018c15fd0948075121f181decd1 When I try to run git log at this stage I get fatal: bad default revision 'HEAD'. What should I do in order to recover my data??? EDIT: klaustopher's suggestion: * *I added a file under /refs/heads called master containing one of the dangling commits. *The msg I got in return was fatal: unable to read tree 3c864da48b16ad0dc5f8ae585380270a708a1e56 *I checked and there is no 3c directory under "objects"... A: Well, you got the objects but git has no idea which is the commit it should interpret as the master. There are three suggestions in the output of git fsck. You could try the following: * *create the .git/refs/heads directory and create a file called master *Put the SHA1 hash of one of the commits in this file *Run git checkout master If that is not the commit you were looking for, put in another sha1 hash in the master-file -- Edit: If those aren't real commits like you described in the comment, than you should maybe go through your objects. With git show 2452845a7b526db3dfbf88c1c2ca05967ef9653a you can see the contents of the file. If it is a commit it will start with the word commit and also have the date, commit message, etc in it. You could maybe write a little shell script to go through all the objects. When you found your commit, put its sha1 in the refs/heads/master file and do what I described above
{ "language": "en", "url": "https://stackoverflow.com/questions/7537714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Declare a retain property in class, will the compiler add [property release] to -dealloc by default? Possible Duplicate: Is releasing memory of Objective-c 2.0 properties required? For example: @interface DataMode : NSObject { NSString * name; } @property (nonatomic, retain) NSString * name; @end Will the compiler automatically add [name release] to -dealloc? - (void) dealloc { [name release]; // if we don't add it , will the compiler add "[name release]"??? [super release]; } A: It depends on which memory management scheme you’re using: * *With garbage collection, you don’t need to release the instance variable that backs the declared property — the garbage collector automatically does that. In fact, you wouldn’t be defining a -dealloc method at all even if you need to do other tasks upon deallocation: the garbage collector sends -finalize instead of -dealloc; *With automatic reference counting (ARC), you wouldn’t define that -dealloc method. ARC will automatically release the instance variable that backs the declared property. You can define a -dealloc method to do other housekeeping tasks if needed but you won’t send [super dealloc]; *With manual memory management, you need to manually release the instance variable that backs the declared property and then send [super dealloc]. A: Since you are adding or rather creating name its your responsibility to release it. So you need to add [name release] in dealloc and also in ViewDidUnLoad use name = nil. ObjectiveC has garbage collection but in iOS garbage collection part has been stripped out. So allocation, deallocation, retain etc. you need to be aware of...
{ "language": "en", "url": "https://stackoverflow.com/questions/7537717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scaling ImageViews For higher res phones I have a few ImageViews located near the bottom of my application. When I run in WVGA (Nexus One), everything lines up nicely with the bottom. When running on another higher res, such as FWVGA, as well as on my Droid 2, there is a space that is left on the bottom of the application. Is there a way to scale imageviews so that they stretch to fill all the space needed in one or multiple directions? At the moment I am using an AbsoluteView and my imageview code looks like. I have tried layout_x and layout_y. <ImageView android:layout_height="400px" android:id="@+id/widget33" android:layout_width="300px" android:background="@drawable/picture1" android:layout_x="-45dp" android:layout_y="216dp"> </ImageView> I have also tried a few other things such as android:baselineAlignBottom android:padding A: You had fixed the height and width of the imageview. If you want to set imageview in your whole screen you can use fill_parent or match_parent if above Android2.2 . And also I am giving you advice to use relative layout instead of Absolute layout. In relative layout you can set Views in relative position so that your view will remains same even if the resolution of the device will increase. And also use unit of length in dp instead of px so that your view will remains same in all screen density.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass variable from jquery to code in c# in my page i have an int variable name mySerial and i want to pass a value from a script mySerial =ui.item.Serial is not working A: You could pass this variable as query string parameter to some controller action: <script type="text/javascript"> var mySerial = '12345'; $.ajax({ url: '@Url.Action("Foo", "Home")', type: 'POST', data: { mySerial: mySerial }, success: function(result) { alert('success'); } }); </script> and the Foo action: [HttpPost] public ActionResult Foo(string mySerial) { ... do something with the serial here } Another possibility is to perform a redirect if you don't want to use AJAX: <script type="text/javascript"> var mySerial = '12345'; var fooUrl = '@Url.Action("Foo", "Home")'; window.location.href = fooUrl + '?mySerial' + encodeURIComponent(mySerial); </script> Or maybe I misunderstood your question and you want to assign your javascript variable to some value coming from the view model? In this case: <script type="text/javascript"> var mySerial = @Html.Raw(Json.Encode(Model.MySerial)); </script> A: you could pass value from your jquery to controller action like this ... $(document).ready(function() { var postdata = { name: "your name", Age: "your age" };// you can pass control values $.ajax({ ur: /home/index, data: postdata, success: function(returndata) { // do something here for the return data... } }); }); in your controller public ActionResult PostedDAta(string myname, string myage) { // do somethign here and return Json back to Jquery code return Json(data,JsonRequestBehaviour.AllowGet); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simulate "Slide to Unlock" in MobileSubstrate There is a way to simulate the Slide To Unlock in the lockscreen? I've been looked for this in SBAwayController, but without any results :( Have anyone an idea? A: I believe (if I understand your question correctly) you want to have the lockbar "unlock itself". For something like that you want to look into SBAwayView, not SBAwayController. In that class there are different methods that interact with the different lockbars. You will want to specifically look at the SBAwayLockBar which is a sublcass of TPBottomLockBar (defined in <TelephonyUI/TPBottomLockBar.h>) You will have to poke around in the headers and see if there is any way to access the lockbar's Knob position. Hope that helped at least a bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make 'datetime' column ordered correctly? I have a column, it's time is 'DATETIME'. I want to output it in the order of timeline, but when I use ORDER BY create_time DESC, '2011-09-10 16:16:04' is behind '2011-07-16 03:20:01'. Seems it is treating datatime column as string. How can I handle this without changing the column type? UPDATE: This is part of my query: SELECT 'bookcomment' AS type ,b.book_id ,b.name ,c.book_id ,c.author_id ,c.content ,c.create_time as create_time ,u.id ,u.name FROM tbl_book AS b, tbl_book_comment AS c, tbl_user AS u WHERE u.id=c.author_id in (1,2) AND b.book_id=c.book_id UNION ALL SELECT 'bookreview' AS type ,b.book_id ,b.name ,re.book_id ,re.author_id ,re.content ,re.create_time as create_time ,u.id ,u.name FROM tbl_book AS b, tbl_book_review AS re, tbl_user AS u WHERE u.id=re.author_id in (1,2) AND b.book_id=re.book_id UNION ALL ... ORDER BY create_time DESC And part of the output: array(7) { ["type"]=> string(16) "new post comment" ["book_id"]=> string(1) "1" ["name"]=> string(9) "Whatever" ["author_id"]=> string(4) "test" ["content"]=> string(19) "2011-07-16 03:20:01" ["create_time"]=> string(1) "3" ["id"]=> string(1) "1" } array(7) { ["type"]=> string(16) "new post comment" ["book_id"]=> string(1) "1" ["name"]=> string(9) "whatever" ["author_id"]=> string(13) "sdfwefwaefwea" ["content"]=> string(19) "2011-05-11 03:33:33" ["create_time"]=> string(1) "3" ["id"]=> string(1) "1" } array(7) { ["type"]=> string(16) "new post comment" ["book_id"]=> string(1) "1" ["name"]=> string(9) "whatever" ["author_id"]=> string(5) "test0" ["content"]=> string(19) "2011-09-10 16:16:04" ["create_time"]=> string(1) "3" ["id"]=> string(1) "1" } array(7) { ["type"]=> string(16) "new post comment" ["book_id"]=> string(1) "1" ["name"]=> string(9) "whatever" ["author_id"]=> string(5) "test1" ["content"]=> string(19) "2011-09-10 16:16:04" ["create_time"]=> string(1) "3" ["id"]=> string(1) "1" } array(7) { ["type"]=> string(16) "new post comment" ["book_id"]=> string(1) "1" ["name"]=> string(9) "whatever" ["author_id"]=> string(5) "test2" ["content"]=> string(19) "2011-09-10 16:16:04" ["create_time"]=> string(1) "3" ["id"]=> string(1) "1" } array(7) { ["type"]=> string(16) "new post comment" ["book_id"]=> string(1) "1" ["name"]=> string(9) "whatever" ["author_id"]=> string(5) "test3" ["content"]=> string(19) "2011-09-10 16:16:04" ["create_time"]=> string(1) "3" ["id"]=> string(1) "1" } array(7) { ["type"]=> string(16) "new post comment" ["book_id"]=> string(1) "1" ["name"]=> string(9) "whatever" ["author_id"]=> string(5) "test4" ["content"]=> string(19) "2011-09-10 16:16:04" ["create_time"]=> string(1) "3" ["id"]=> string(1) "1" } A: You appear to have the data in the wrong columns. In your output sample create_time is 3 for all of them, so the order is undefined. Double-check data is in the right columns? A: try using ORDER BY CONVERT (create_time, DATETIME) DESC BUT beware that this costs some performance... changing the column type is IMHO the better option !
{ "language": "en", "url": "https://stackoverflow.com/questions/7537721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error When getting List from a class I have a problem that, I have a serializable class which sets and gets multiple lists. I added a list into that but when I want to get that list from getter method it returns NullPointerException. That's why I mentioned here Error and Setter and Getter Methods for explaining the problem and How I retrive it.I don't know why and don't know how it will be removed? Can any one help me about this problem? Error Stack: 09-24 13:04:18.923: ERROR/AndroidRuntime(529): FATAL EXCEPTION: main 09-24 13:04:18.923: ERROR/AndroidRuntime(529): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.equinix.android.common/com.equinix.android.showmyorders.ShowMyOrders}: java.lang.NullPointerException 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.os.Handler.dispatchMessage(Handler.java:99) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.os.Looper.loop(Looper.java:123) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at java.lang.reflect.Method.invokeNative(Native Method) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at java.lang.reflect.Method.invoke(Method.java:521) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at dalvik.system.NativeStart.main(Native Method) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): Caused by: java.lang.NullPointerException 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at com.equinix.android.showmyorders.ShowMyOrders.onCreate(ShowMyOrders.java:87) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 09-24 13:04:18.923: ERROR/AndroidRuntime(529): ... 11 more Class for Setting and Getting List: package com.equinix.android.model; import java.io.Serializable; import java.util.List; public class BaseIBXValues implements Serializable{ private static final long serialVersionUID = 7526472295622776147L; private List<String> IBXId; private List<String> IBXName; private List<String> IBXNaturalKey; public List<String> getIBXId() { return IBXId; } public void setIBXId(List<String> IBXId) { this.IBXId = IBXId; } public List<String> getIBXName() { return IBXName; } public void setIBXName(List<String> IBXName) { this.IBXName = IBXName; } public List<String> getIBXNaturalKey() { return IBXNaturalKey; } public void setIBXNaturalKey(List<String> IBXNaturalKey) { this.IBXNaturalKey = IBXNaturalKey; } } **Code for Setting the value of arraylist:** public class Parse_Json { String json_String; List<String> IBXId; BaseIBXValues ibx;------> It is the class where setter and getter mentioned public Parse_Json(String json_String) { this.json_String = json_String; } public void parse() { ibx = new BaseIBXValues(); try{ JSONObject ja = new JSONObject(json_String); JSONArray jo = ja.getJSONArray("ibx"); for(int i=0;i<jo.length();i++) { JSONObject j_data = jo.getJSONObject(i); System.out.println("The id is:"+j_data.getString("id")); IBXId.add(j_data.getString("id")); LoginScreen.id.add(j_data.getString("id")); System.out.println("The Name is:"+j_data.getString("name")); LoginScreen.name.add(j_data.getString("name")); System.out.println("The naturalKey is:"+j_data.getString("naturalKey")); LoginScreen.naturalKey.add(j_data.getString("naturalKey")); } }catch(Exception e) { e.printStackTrace(); } ibx.setIBXId(IBXId);------------> set the list } Get the List from Getter: ibx = new BaseIBXValues(); ibId = ibx.getIBXId(); for(int i=0;i<6;i++) { System.out.println("The IBX ID:"+ibId.get(i)); } A: Few things to note: In the Parse_Json class: List<String> IBXId; IBXID is never intiallized so it is null. So later when it tries to add values to IBXId: IBXId.add(j_data.getString("id")); This will throw a NullPointerException. But if your JSONArray jo = ja.getJSONArray("ibx"); returns a jo of size 0, the line ibx.setIBXId(IBXId); will set IBXId to null In the following code: ibId = ibx.getIBXId(); for(int i=0;i<6;i++) { System.out.println("The IBX ID:"+ibId.get(i)); } ibId is null because in the BaseIBXValues class, the line private List<String> IBXId; doesnt initialize IBXId, so it s value is null so calling ibId.get(i) to it will result in a NullPointerException EDIT See your code modified here: public class Parse_Json { String json_String; List<String> IBXId = new ArrayList<String>(); BaseIBXValues ibx;------> It is the class where setter and getter mentioned But when you call the getter ibId = ibx.getIBXId(); for(int i=0;i<6;i++) { System.out.println("The IBX ID:"+ibId.get(i)); } , you can make sure that you have a non-null value ibId = ibx.getIBXId(); If(ibId != null) { for(String index : ibId) { System.out.println("The IBX ID:"+index); } } Edited List<String> ibId=Collections.emptyList(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.showmyorders); ibx = new BaseIBXValues(); ibId = ibx.getIBXId(); if(ibId != null) { for(String index : ibId) { System.out.println("The IBX ID:"+index); } } EDIT: This should be: public class BaseIBXValues implements Serializable{ private static final long serialVersionUID = 7526472295622776147L; private List<String> IBXId = new ArrayList<String>(); // initialize to empty array of string private List<String> IBXName; When creating the new BaseIBXValues object, ibx = new BaseIBXValues(); ibId = ibx.getIBXId(); ibId should be an empty array of string
{ "language": "en", "url": "https://stackoverflow.com/questions/7537741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extracting info from plain text using regexps or other, more efficient method I need to extract data from plain text returned from stripping HTML tags from a webpage. The tags were stripped out because the page consists of tabular data, but with tables nested into tables, nested into tables, and so on (really ugly HTML code). After cleaning the code (with HTML Tidy) and stripping out the tags, the site returns info like this: Visitor ID : &nbsp; 123456789 &nbsp; HostName: 127.0.01 &nbsp;&nbsp;&nbsp; IP :&nbsp; 127.0.0.1 &nbsp;First Visit -> Entry Page :&nbsp;&nbsp; First Visit Entry Page Title Example First Visit -> Referrer: http://somepage.com First Visit : 302 Day(s) &nbsp;&nbsp; Last Visit : &nbsp; 09/23/2011 &nbsp; ISP: Initech &nbsp; Country: &nbsp;Some country Country: &nbsp;Some &nbsp;country Browser: Chrome Screen Res: Unknow 4 Billion colors (32 bit) &nbsp; Javascript: Enabled&nbsp; Page Views: 1&nbsp; File Downloaded: 0&nbsp; Daily Visits: 1 Visit Length: 0 minutes 0 seconds Entry Page: Entry page title Exit Page: Exit page title Referring URL: No (As you can see, a very long and random mess) And I want to turn it into this: Visitor ID: 123456789 HostName: 127.0.01 IP: 127.0.01 First Visit: 302 Day(s) First Visit -> Entry Page: First Visit Entry Page Title Example First Visit -> Referrer: http://somepage.com Last Visit: 09/23/2011 ISP: Initech Country: Some country Country: Some country Browser: Chrome Screen Res: Unknow 4 Billion colors (32 bit) Javascript: Enabled Page Views: 1 File Downloaded: 0 Daily Visits: 1 Visit Length: 1 minute(s) 26 second Entry Page: Entry page title Exit Page: Exit page title Referring URL: No I'm currently using regexps to remove extra whitespace and try to sort the data. So far, it's almost working using this: $patterns = array("/HostName\s*:/", "/IP\s*:/", "/First\s+Visit\s+->\s+Entry\s+Page\s*:/", "/First\s+Visit\s+->\s+Referrer\s*:/", "/First\s+Visit\s*:/", "/\bLast\s+Visit\s*:/", "/\bISP\s*:/", "/\bCountry\s*:/", "/\bBrowser\s*:/", "/\bScreen\s*Res\s*:/", "/\bJavascript\s*:/", "/\bPage\s+Views\s*:/", "/\bFile\s+Downloaded\s*:/", "/\bDaily\s+Visits\s*:/", "/\bVisit\s+Length\s*:/", "/\bEntry\s+Page\s*:/", "/\bExit\s+Page\s*:/", "/\bReferring\s+URL\s*:/", "/\bFrom\s+Campaign\s*:/" ); $replacements = array("\nHostName:", "\nIP:", "\nFirst Visit -> Entry Page:", "\nFirst Visit -> Referrer:", "\nFirst Visit:", "\nLast Visit:", "\nISP:", "\nCountry:", "\nBrowser:", "\nScreen Res:", "\nJavascript:", "\nPage Views:", "\nFile Downloaded:", "\nDaily Visits:", "\nVisit Length:", "\nEntry Page:", "\nExit Page:", "\nReferring URL:", "\nFrom Campaign:" ); ksort( $patterns ); ksort( $replacements ); $fixed_text = preg_replace ( $patterns, $replacements, $ugly_mess ); However, this isn't really working as expected. Note that some fields are similar, and the regexp fails to work, resulting in something like this: Visitor ID: 123456789 HostName: 127.0.0.1 IP: 127.0.0.1 Last Visit: 302 Day(s) First Visit: 10 June 2010 First Visit -> Entry Page: First Visit Entry Page Title Example First Visit -> Referrer: http://somepage .com ISP: Initech Country: Some Country Country: Some Country Browser: Chrome Screen Res: Unknow 4 Billion colors (32 bit) Javascript: Enabled Page Views: 1 File Downloaded: 0 Daily Visits: 1 Visit Length: 1 minute(s) 26 second Entry Page: Entry page title Exit Page: Exit page title Referring URL: No I might be going about this the wrong way, so that's why I'm asking for suggestions or fixes to the current code. Any ideas, please? A: Instead of doing it with replace pattern, what if you use match. I'm using javascript, but you could easily change it back to PHP. var pattern = "^(?:"; pattern += "(?:Visitor\\s*ID\\s*:\\s*(\\d+)\\s*)"; pattern += "|(?:HostName\s*:\\s*([^ ]+)\\s*)"; pattern += "|(?:IP\\s*:\\s*([^ ]+)\\s*)"; pattern += "|(?:First\\s*Visit\\s*->\\s*Entry Page\\s*:\\s*(.+?)\\s*(?=First\\s*Visit\\s*->))"; pattern += "|(?:First\\s*Visit\\s*->\\s*Referrer\\s*:\\s*(.+?)\\s*(?=First\\s*Visit\\s*:))"; pattern += "|(?:First\\s*Visit\\s*:\\s*(\\d+)\\s*Day\\(s\\)\\s*)"; pattern += "|(?:Last\\s*Visit\\s*:\\s*(\\d+/\\d+/\\d+)\\s*)"; pattern += "|(?:ISP\\s*:\\s*(.+?)\\s*(?=Country\\s*:))"; pattern += "|(?:Country\\s*:\\s*(.+?)\\s*(?=(?:Country|Browser)\\s*:))"; pattern += "|(?:Browser\\s*:\\s*(.+?)\\s*(?=Screen\\s*Res\\s*:))"; pattern += "|(?:Screen\\s*Res\\s*:\\s*(.+?)\\s*(?=Javascript\\s*:))"; pattern += "|(?:Javascript\\s*:\\s*(.+?)\\s*(?=Page\\s*Views\\s*:))"; pattern += "|(?:Page\\s*Views\\s*:\\s*(\\d+)\\s*)"; pattern += "|(?:File\\s*Downloaded\\s*:\\s*(\\d+)\\s*)"; pattern += "|(?:Daily\\s*Visits\\s*:\\s*(\\d+)\\s*)"; pattern += "|(?:Visit\\s*Length\\s*:\\s*((?:\\d+ (?:hours|minutes|seconds)\\s*)+))"; pattern += ")+"; var regex = new RegExp(pattern); var content = readData().replace(/&nbsp;/g, ""); var match = content.match(regex); echo("Visitor Id: " + match[1]); echo("Hostname: " + match[2]); echo("IP: " + match[3]); // continue on...
{ "language": "en", "url": "https://stackoverflow.com/questions/7537748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: datetime problem in objective c currentDateTime = [NSDate date]; dateFormatter = [[NSDateFormatter alloc]init] ; [dateFormatter setDateFormat:@"yyyy-mm-dd hh:mm"]; // 1999-12-12 14:50 dateInString = [dateFormatter stringFromDate:currentDateTime]; metTime.text=dateInString; NSLog(@"date %@", dateInString); I try send the current time to web service method as a string paramater. I can see it but when pass dateInString I got an error such as System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.Convert.ToDateTime(String value) at MrkService.MrkService.AddMeetingInfo(String phoId, Int32 metId, Int32 cusId, Int32 metTyp, Int32 metRes, String desc, String contc, String endTime) --- End of inner exception stack trace --- is there anyone know this problem (web service method parameter is string not date) A: This pattern looks very wrong to me: yyyy-mm-dd hh:mm See how you're using "mm" twice? And "hh" normally means the 12 hour clock... I suspect you want yyyy-MM-dd HH:mm where MM means the month (not the minute) and HH means the 24 hour clock. That's assuming that iOS date and time patterns work similarly to other platforms... In fact, you may need to make further changes to the pattern - for instance to include seconds, and possibly a T, e.g. yyyy-MM-ddTHH:mm:ss
{ "language": "en", "url": "https://stackoverflow.com/questions/7537753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read number from a file and replace it with another number 12 23 34 45 56 34 23 56 21 43 12 57 98 34 12 The above is the content of a txt file. With C, i can use fgetc(myFile) to get the first integer and store into an integer variable. I will check whether it is 12. if it is 12, i want to replace with 25. How do i exactly replace it a certain number. How do i rewrite a certain part of it? Or do i store every number into an array, replace all 12s with another numbers and overwrite the whole file?? A: If it's a small file , to overwrite the whole file is a good idea and easier. If it's not limited in c language, you can try powerful tools like "sed" or some script language. A: Save result to another file, than renames it. This code opens homework.txt, replaces all 12 -> 25 and writes result to homework_new.txt #include <stdio.h> #include <string.h> #define MAXBUF 42 #define HOMEWORKFILE "homework.txt" #define HOMEWORKNEWFILE "homework_new.txt" int main(int argc, char **argv) { char buf[MAXBUF+1]; char str[MAXBUF+1]; FILE *hw; FILE *hw_new; int length; int i, j; int number; char is_first; int n_line = 0; hw = fopen(HOMEWORKFILE, "r"); hw_new = fopen(HOMEWORKNEWFILE, "w"); if (!hw) { fprintf(stderr, "File not found: %s\n", HOMEWORKFILE); return 5; } while(!feof(hw)) if (fgets(buf, MAXBUF, hw) != NULL) { length = strlen(buf); j = 0; str[0] = 0; is_first = 1; n_line++; /* parse string */ for(i = 0; i < strlen(buf); ++i) { if (isblank(buf[i]) || buf[i] == '\0' || buf[i] == '\n') { str[j] = 0; number = atoi(str); if (is_first) is_first = 0; else fprintf(hw_new, " "); if (number == 12) fprintf(hw_new, "%d", 25); else fprintf(hw_new, "%d", number); j = 0; } else if (isdigit(buf[i])) { str[j++] = buf[i]; } else { fprintf(stderr, "bad input on line %d '%s'\n", n_line, buf); return 100; } } fprintf(hw_new, "\n"); } fclose(hw_new); fclose(hw); return 0; } A: Here's a list: fgets ftell fseek fputs Note that you need to ensure the correct lengths of the data written, in order to overwrite exactly what you want. Another option would be, as you said, to overwrite the whole file, then you also need freopen
{ "language": "en", "url": "https://stackoverflow.com/questions/7537754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }