qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
197,307 |
<p>What would you recommend to search a sql server table (varchar(max) column) for a term?</p>
<p>Let's say, like in ebay, if you search for "wii brand new", you get results like "Brand New Nintendo Wii Fit Game + Balance Board Bundle", "Wii Fit (Wii) BRAND NEW WII FIT GAME + BALANCE BOARD".</p>
<p>I think it basically searches every word and returns the ones that contains all the words, what would you recommend?</p>
|
[
{
"answer_id": 197313,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>You are looking for fulltext indexing, it allows you to do more advanced querying than regular expressions or like.</p>\n\n<p>Check <a href=\"http://www.developer.com/db/article.php/3446891\" rel=\"noreferrer\">this</a> article for a quick introduction, the instructions are for SQL Server 2000, where it is a little harder to setup than in 2005 or 2008.</p>\n\n<p>Relevant quote:</p>\n\n<pre>\n With full-text searching, you can perform many other types of search:\n\n * Two words near each other\n * Any word derived from a particular root (for example run, ran, or running)\n * Multiple words with distinct weightings\n * A word or phrase close to the search word or phrase\n</pre>\n"
},
{
"answer_id": 197314,
"author": "Matt Brown",
"author_id": 7272,
"author_profile": "https://Stackoverflow.com/users/7272",
"pm_score": 2,
"selected": false,
"text": "<p>Depends on what you are trying to do. For a simple search, you could just do \n<code>select * from table where field like '%word%'</code>. But if this is some sort of application feature, you want to look into a full tet search application. It can store words that appear in that field as indexes and then search accross those words instead of using that field.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17648/"
] |
What would you recommend to search a sql server table (varchar(max) column) for a term?
Let's say, like in ebay, if you search for "wii brand new", you get results like "Brand New Nintendo Wii Fit Game + Balance Board Bundle", "Wii Fit (Wii) BRAND NEW WII FIT GAME + BALANCE BOARD".
I think it basically searches every word and returns the ones that contains all the words, what would you recommend?
|
You are looking for fulltext indexing, it allows you to do more advanced querying than regular expressions or like.
Check [this](http://www.developer.com/db/article.php/3446891) article for a quick introduction, the instructions are for SQL Server 2000, where it is a little harder to setup than in 2005 or 2008.
Relevant quote:
```
With full-text searching, you can perform many other types of search:
* Two words near each other
* Any word derived from a particular root (for example run, ran, or running)
* Multiple words with distinct weightings
* A word or phrase close to the search word or phrase
```
|
197,310 |
<p>I want to do this (no particular language):</p>
<pre><code>print(foo.objects.bookdb.books[12].title);
</code></pre>
<p>or this:</p>
<pre><code>book = foo.objects.bookdb.book.new();
book.title = 'RPC for Dummies';
book.save();
</code></pre>
<p>Where foo actually is a service connected to my program via some IPC, and to access its methods and objects, some layer actually sends and receives messages over the network.</p>
<p>Now, I'm not really looking for an IPC mechanism, as there are plenty to choose from. It's likely not to be XML based, but rather s. th. like Google's protocol buffers, dbus or CORBA. What I'm unsure about is how to structure the application so I can access the IPC just like I would any object.</p>
<p>In other words, how can I have OOP that maps transparently over process boundaries?</p>
<p>Not that this is a design question and I'm still working at a pretty high level of the overall architecture. So I'm pretty agnostic yet about which language this is going to be in. C#, Java and Python are all likely to get used, though.</p>
|
[
{
"answer_id": 197322,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>I think the way to do what you are requesting is to have all object communication regarded as message passing. This is how object methods are handled in ruby and smalltalk, among others. </p>\n\n<p>With message passing (rather than method calling) as your object communication mechanism, then operations such as calling a method that didn't exist when you wrote the code becomes sensible as the object can do something sensible with the message anyway (check for a remote procedure, return a value for a field with the same name from a database, etc, or throw a 'method not found' exception, or anything else you could think of).</p>\n\n<p>It's important to note that for languages that don't use this as a default mechanism, you can do message passing anyway (every object has a 'handleMessage' method) but you won't get the syntax niceties, and you won't be able to get IDE help without some extra effort on your part to get the IDE to parse your handleMessage method to check for valid inputs.</p>\n"
},
{
"answer_id": 197380,
"author": "edgar.holleis",
"author_id": 24937,
"author_profile": "https://Stackoverflow.com/users/24937",
"pm_score": -1,
"selected": true,
"text": "<p>You shouldn't do it! It is very important for programmers to see and feel the difference between an IPC/RPC and a local method call in the code. If you make it so, that they don't have to think about it, they won't think about it, and that will lead to very poorly performing code.</p>\n\n<p>Think of:</p>\n\n<pre><code>foreach o, o.isGreen in someList { \n o.makeBlue; \n}\n</code></pre>\n\n<p>The programmer assumes that the loops takes a few nanoseconds to complete, instead it takes close to a second if someList happens to be remote.</p>\n"
},
{
"answer_id": 210914,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>Read up on Java's <a href=\"http://java.sun.com/docs/books/tutorial/rmi/overview.html\" rel=\"nofollow noreferrer\">RMI</a> -- the introductory material shows how you can have a local definition of a remote object.</p>\n\n<p>The trick is to have two classes with identical method signatures. The local version of the class is a facade over some network protocol. The remote version receives requests over the network and does the actual work of the object. </p>\n\n<p>You can define a pair of classes so a client can have</p>\n\n<pre><code>foo= NonLocalFoo( \"http://host:port\" )\nfoo.this= \"that\"\nfoo.save()\n</code></pre>\n\n<p>And the server receives set_this() and save() method requests from a client connection. The server side is (generally) non-trivial because you have a bunch of discovery and instance management issues.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] |
I want to do this (no particular language):
```
print(foo.objects.bookdb.books[12].title);
```
or this:
```
book = foo.objects.bookdb.book.new();
book.title = 'RPC for Dummies';
book.save();
```
Where foo actually is a service connected to my program via some IPC, and to access its methods and objects, some layer actually sends and receives messages over the network.
Now, I'm not really looking for an IPC mechanism, as there are plenty to choose from. It's likely not to be XML based, but rather s. th. like Google's protocol buffers, dbus or CORBA. What I'm unsure about is how to structure the application so I can access the IPC just like I would any object.
In other words, how can I have OOP that maps transparently over process boundaries?
Not that this is a design question and I'm still working at a pretty high level of the overall architecture. So I'm pretty agnostic yet about which language this is going to be in. C#, Java and Python are all likely to get used, though.
|
You shouldn't do it! It is very important for programmers to see and feel the difference between an IPC/RPC and a local method call in the code. If you make it so, that they don't have to think about it, they won't think about it, and that will lead to very poorly performing code.
Think of:
```
foreach o, o.isGreen in someList {
o.makeBlue;
}
```
The programmer assumes that the loops takes a few nanoseconds to complete, instead it takes close to a second if someList happens to be remote.
|
197,319 |
<p>I'm trying to create and retrieve a BLOB in a MySQL table via Kohana's ORM library.</p>
<p>The code looks something like:</p>
<pre><code>$attachment = new Attachment_Model();
$attachment->name = $info['FileName'];
$attachment->size = strlen($info['Data']);
$attachment->data = $info['Data'];
$attachment->mime_type = $info['content-type'];
$attachment->save();
</code></pre>
<p>I've verified that the data is OK at this point by outputting it to a file. However, when I retrieve the data it comes out corrupted. I've managed to narrow this down a bit more - I've used the MySQL query tool to extract the data as held in the database and I can verify that the data in the database is corrupt, so the problem must be on the INSERT.</p>
<p>Also, the files inputted aren't always corrupt - smaller files (such as images) tend to be OK.</p>
<p>Anyone have any ideas?</p>
|
[
{
"answer_id": 197349,
"author": "thr",
"author_id": 452521,
"author_profile": "https://Stackoverflow.com/users/452521",
"pm_score": 0,
"selected": false,
"text": "<p>Wild guess, but: probably because the kohana model layer inserts all data as character data instead of binary, which will cause you troubles when saving/retrieving BLOB objects.</p>\n"
},
{
"answer_id": 197356,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>It turns out that, in this case, I was using the BLOB data type.</p>\n\n<p>The BLOB data type truncates data at 65535 characters (silently, without throwing an error!)</p>\n\n<p>I've upped it to a MEDIUMBLOB (which has a max length of 16777215 characters), and it seems to work OK!</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to create and retrieve a BLOB in a MySQL table via Kohana's ORM library.
The code looks something like:
```
$attachment = new Attachment_Model();
$attachment->name = $info['FileName'];
$attachment->size = strlen($info['Data']);
$attachment->data = $info['Data'];
$attachment->mime_type = $info['content-type'];
$attachment->save();
```
I've verified that the data is OK at this point by outputting it to a file. However, when I retrieve the data it comes out corrupted. I've managed to narrow this down a bit more - I've used the MySQL query tool to extract the data as held in the database and I can verify that the data in the database is corrupt, so the problem must be on the INSERT.
Also, the files inputted aren't always corrupt - smaller files (such as images) tend to be OK.
Anyone have any ideas?
|
It turns out that, in this case, I was using the BLOB data type.
The BLOB data type truncates data at 65535 characters (silently, without throwing an error!)
I've upped it to a MEDIUMBLOB (which has a max length of 16777215 characters), and it seems to work OK!
|
197,362 |
<p>I have a products table that contains a FK for a category, the Categories table is created in a way that each category can have a parent category, example:</p>
<pre><code>Computers
Processors
Intel
Pentium
Core 2 Duo
AMD
Athlon
</code></pre>
<p>I need to make a select query that if the selected category is Processors, it will return products that is in Intel, Pentium, Core 2 Duo, Amd, etc...</p>
<p>I thought about creating some sort of "cache" that will store all the categories in the hierarchy for every category in the db and include the "IN" in the where clause. Is this the best solution?</p>
|
[
{
"answer_id": 197373,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 0,
"selected": false,
"text": "<p>I have done similar things in the past, first querying for the category ids, then querying for the products \"IN\" those categories. Getting the categories is the hard bit, and you have a few options:</p>\n\n<ul>\n<li>If the level of nesting of categories is known or you can find an upper bound: Build a horrible-looking SELECT with lots of JOINs. This is fast, but ugly and you need to set a limit on the levels of the hierarchy.</li>\n<li>If you have a relatively small number of total categories, query them all (just ids, parents), collect the ids of the ones you care about, and do a SELECT....IN for the products. This was the appropriate option for me.</li>\n<li>Query up/down the hierarchy using a series of SELECTs. Simple, but relatively slow.</li>\n<li>I believe recent versions of SQLServer have some support for recursive queries, but haven't used them myself.</li>\n</ul>\n\n<p>Stored procedures can help if you don't want to do this app-side.</p>\n"
},
{
"answer_id": 197389,
"author": "Simon",
"author_id": 22404,
"author_profile": "https://Stackoverflow.com/users/22404",
"pm_score": 0,
"selected": false,
"text": "<p>What you want to find is the transitive closure of the category \"parent\" relation. I suppose there's no limitation to the category hierarchy depth, so you can't formulate a single SQL query which finds all categories. What I would do (in pseudocode) is this:</p>\n\n<pre><code>categoriesSet = empty set\nwhile new.size > 0:\n new = select * from categories where parent in categoriesSet\n categoriesSet = categoriesSet+new\n</code></pre>\n\n<p>So just keep on querying for children until no more are found. This behaves well in terms of speed unless you have a degenerated hierarchy (say, 1000 categories, each a child of another), or a large number of total categories. In the second case, you could always work with temporary tables to keep data transfer between your app and the database small.</p>\n"
},
{
"answer_id": 197403,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe something like:</p>\n\n<pre><code>select *\nfrom products\nwhere products.category_id IN\n (select c2.category_id \n from categories c1 inner join categories c2 on c1.category_id = c2.parent_id\n where c1.category = 'Processors'\n group by c2.category_id)\n</code></pre>\n\n<p>[EDIT] If the category depth is greater than one this would form your innermost query. I suspect that you could design a stored procedure that would drill down in the table until the ids returned by the inner query did not have children -- probably better to have an attribute that marks a category as a terminal node in the hierarchy -- then perform the outer query on those ids.</p>\n"
},
{
"answer_id": 197503,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 0,
"selected": false,
"text": "<pre><code>CREATE TABLE #categories (id INT NOT NULL, parentId INT, [name] NVARCHAR(100))\nINSERT INTO #categories\n SELECT 1, NULL, 'Computers'\n UNION\nSELECT 2, 1, 'Processors'\n UNION\nSELECT 3, 2, 'Intel'\n UNION\nSELECT 4, 2, 'AMD'\n UNION\nSELECT 5, 3, 'Pentium'\n UNION\nSELECT 6, 3, 'Core 2 Duo'\n UNION\nSELECT 7, 4, 'Athlon'\nSELECT * \n FROM #categories\nDECLARE @id INT\n SET @id = 2\n ; WITH r(id, parentid, [name]) AS (\n SELECT id, parentid, [name] \n FROM #categories c \n WHERE id = @id\n UNION ALL\n SELECT c.id, c.parentid, c.[name] \n FROM #categories c JOIN r ON c.parentid=r.id\n )\nSELECT * \n FROM products \n WHERE p.productd IN\n(SELECT id \n FROM r)\nDROP TABLE #categories \n</code></pre>\n\n<p>The last part of the example isn't actually working if you're running it straight like this. Just remove the select from the products and substitute with a simple SELECT * FROM r</p>\n"
},
{
"answer_id": 197594,
"author": "Steven Robbins",
"author_id": 26507,
"author_profile": "https://Stackoverflow.com/users/26507",
"pm_score": 2,
"selected": false,
"text": "<p>Looks like a job for a Common Table Expression.. something along the lines of:</p>\n\n<pre><code>with catCTE (catid, parentid)\nas\n(\nselect cat.catid, cat.catparentid from cat where cat.name = 'Processors'\nUNION ALL\nselect cat.catid, cat.catparentid from cat inner join catCTE on cat.catparentid=catcte.catid\n)\nselect distinct * from catCTE\n</code></pre>\n\n<p>That should select the category whose name is 'Processors' and any of it's descendents, should be able to use that in an IN clause to pull back the products.</p>\n"
},
{
"answer_id": 197597,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 4,
"selected": true,
"text": "<p>The best solution for this is at the database design stage. Your categories table needs to be a <em>Nested Set</em>. The article <a href=\"http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/\" rel=\"nofollow noreferrer\">Managing Hierarchical Data in MySQL</a> is not that MySQL specific (despite the title), and gives a great overview of the different methods of storing a hierarchy in a database table.</p>\n\n<h1>Executive Summary:</h1>\n\n<h2>Nested Sets</h2>\n\n<ul>\n<li>Selects are easy for any depth</li>\n<li>Inserts and deletes are hard</li>\n</ul>\n\n<h2>Standard parent_id based hierarchy</h2>\n\n<ul>\n<li>Selects are based on inner joins (so get hairy fast)</li>\n<li>Inserts and deletes are easy</li>\n</ul>\n\n<p>So based on your example, if your hierarchy table was a nested set your query would look something like this:</p>\n\n<pre><code>SELECT * FROM products \n INNER JOIN categories ON categories.id = products.category_id \nWHERE categories.lft > 2 and categories.rgt < 11\n</code></pre>\n\n<p>the 2 and 11 are the left and right respectively of the <code>Processors</code> record.</p>\n"
},
{
"answer_id": 197607,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This should recurse down all the 'child' catagories starting from a given catagory.</p>\n\n<pre><code>DECLARE @startingCatagoryId int\nDECLARE @current int\nSET @startingCatagoryId = 13813 -- or whatever the CatagoryId is for 'Processors'\n\nCREATE TABLE #CatagoriesToFindChildrenFor\n(CatagoryId int)\n\nCREATE TABLE #CatagoryTree\n(CatagoryId int)\n\nINSERT INTO #CatagoriesToFindChildrenFor VALUES (@startingCatagoryId)\n\nWHILE (SELECT count(*) FROM #CatagoriesToFindChildrenFor) > 0\nBEGIN\n SET @current = (SELECT TOP 1 * FROM #CatagoriesToFindChildrenFor)\n\n INSERT INTO #CatagoriesToFindChildrenFor\n SELECT ID FROM Catagory WHERE ParentCatagoryId = @current AND Deleted = 0\n\n INSERT INTO #CatagoryTree VALUES (@current)\n DELETE #CatagoriesToFindChildrenFor WHERE CatagoryId = @current\nEND\n\nSELECT * FROM #CatagoryTree ORDER BY CatagoryId\n\nDROP TABLE #CatagoriesToFindChildrenFor\nDROP TABLE #CatagoryTree\n</code></pre>\n"
},
{
"answer_id": 206665,
"author": "cheeves",
"author_id": 15826,
"author_profile": "https://Stackoverflow.com/users/15826",
"pm_score": 0,
"selected": false,
"text": "<p>i like to use a stack temp table for hierarchal data. \nhere's a rough example - </p>\n\n<pre><code>-- create a categories table and fill it with 10 rows (with random parentIds)\nCREATE TABLE Categories ( Id uniqueidentifier, ParentId uniqueidentifier )\nGO\n\nINSERT\nINTO Categories\nSELECT NEWID(),\n NULL \nGO\n\nINSERT\nINTO Categories\nSELECT TOP(1)NEWID(),\n Id\nFROM Categories\nORDER BY Id\nGO 9\n\n\nDECLARE @lvl INT, -- holds onto the level as we move throught the hierarchy\n @Id Uniqueidentifier -- the id of the current item in the stack\n\nSET @lvl = 1\n\nCREATE TABLE #stack (item UNIQUEIDENTIFIER, [lvl] INT)\n-- we fill fill this table with the ids we want\nCREATE TABLE #tmpCategories (Id UNIQUEIDENTIFIER)\n\n-- for this example we’ll just select all the ids \n-- if we want all the children of a specific parent we would include it’s id in\n-- this where clause\nINSERT INTO #stack SELECT Id, @lvl FROM Categories WHERE ParentId IS NULL\n\nWHILE @lvl > 0\nBEGIN -- begin 1\n\n IF EXISTS ( SELECT * FROM #stack WHERE lvl = @lvl )\n BEGIN -- begin 2\n\n SELECT @Id = [item]\n FROM #stack\n WHERE lvl = @lvl\n\n INSERT INTO #tmpCategories\n SELECT @Id\n\n DELETE FROM #stack\n WHERE lvl = @lvl\n AND item = @Id\n\n INSERT INTO #stack\n SELECT Id, @lvl + 1\n FROM Categories\n WHERE ParentId = @Id\n\n IF @@ROWCOUNT > 0\n BEGIN -- begin 3\n SELECT @lvl = @lvl + 1\n END -- end 3\n END -- end 2\n ELSE\n SELECT @lvl = @lvl - 1\n\nEND -- end 1\n\nDROP TABLE #stack\n\nSELECT * FROM #tmpCategories\nDROP TABLE #tmpCategories\nDROP TABLE Categories\n</code></pre>\n\n<p>there is a good explanation here <a href=\"http://msdn.microsoft.com/en-us/library/aa172799(SQL.80).aspx\" rel=\"nofollow noreferrer\">link text</a></p>\n"
},
{
"answer_id": 206715,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "<p>My answer to another question from a couple days ago applies here... <a href=\"https://stackoverflow.com/questions/191208/is-recursion-good-in-sql-server#191635\">recursion in SQL</a></p>\n\n<p>There are some methods in the book which I've linked which should cover your situation nicely.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17648/"
] |
I have a products table that contains a FK for a category, the Categories table is created in a way that each category can have a parent category, example:
```
Computers
Processors
Intel
Pentium
Core 2 Duo
AMD
Athlon
```
I need to make a select query that if the selected category is Processors, it will return products that is in Intel, Pentium, Core 2 Duo, Amd, etc...
I thought about creating some sort of "cache" that will store all the categories in the hierarchy for every category in the db and include the "IN" in the where clause. Is this the best solution?
|
The best solution for this is at the database design stage. Your categories table needs to be a *Nested Set*. The article [Managing Hierarchical Data in MySQL](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) is not that MySQL specific (despite the title), and gives a great overview of the different methods of storing a hierarchy in a database table.
Executive Summary:
==================
Nested Sets
-----------
* Selects are easy for any depth
* Inserts and deletes are hard
Standard parent\_id based hierarchy
-----------------------------------
* Selects are based on inner joins (so get hairy fast)
* Inserts and deletes are easy
So based on your example, if your hierarchy table was a nested set your query would look something like this:
```
SELECT * FROM products
INNER JOIN categories ON categories.id = products.category_id
WHERE categories.lft > 2 and categories.rgt < 11
```
the 2 and 11 are the left and right respectively of the `Processors` record.
|
197,372 |
<p>I have a JUnit 3.x TestCase which I would like to be able to parameterize. I'd like to parametrize the entire <code>TestCase</code> (including the fixture). However, the <code>TestSuite.addTestSuite()</code> method does not allow be to pass a <code>TestCase</code> object, just a class:</p>
<pre><code> TestSuite suite = new TestSuite("suite");
suite.addTestSuite(MyTestCase.class);
</code></pre>
<p>I would like to be able to pass a parameter (a string) to the MyTestCase instance which is created when the test runs. As it is now, I have to have a separate class for each parameter value.</p>
<p>I tried passing it an anynomous subclass:</p>
<pre><code> MyTestCase testCase = new MyTestCase() {
String getOption() {
return "some value";
}
}
suite.addTestSuite(testCase.getClass());
</code></pre>
<p>However, this fails with the assertion:</p>
<pre><code> ... MyTestSuite$1 has no public constructor TestCase(String name) or TestCase()`
</code></pre>
<p>Any ideas? Am I attacking the problem the wrong way?</p>
|
[
{
"answer_id": 197374,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 3,
"selected": true,
"text": "<p>If this is Java 5 or higher, you might want to consider switching to JUnit 4, which has support for parameterized test cases built in.</p>\n"
},
{
"answer_id": 197656,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "<p>Rather than create a parameterized test case for the multiple/different backends you want to test against, I would look into making my test cases abstract. Each new implementation of your API would need to supply an implementing TestCase class.</p>\n\n<p>If you currently have a test method that looks something like</p>\n\n<pre><code>public void testSomething() {\n API myAPI = new BlahAPI();\n assertNotNull(myAPI.something());\n}\n</code></pre>\n\n<p>just add an abstract method to the TestCase that returns the specific API object to use.</p>\n\n<pre><code>public abstract class AbstractTestCase extends TestCase {\n public abstract API getAPIToTest();\n\n public void testSomething() {\n API myAPI = getAPIToTest();\n assertNotNull(myAPI.something());\n }\n\n public void testSomethingElse() {\n API myAPI = getAPIToTest();\n assertNotNull(myAPI.somethingElse());\n }\n}\n</code></pre>\n\n<p>Then the TestCase for the new implementation you want to test only has to implement your AbstractTestCase and supply the concrete implementation of the API class:</p>\n\n<pre><code>public class ImplementationXTestCase extends AbstractTestCase{\n\n public API getAPIToTest() {\n return new ImplementationX();\n }\n}\n</code></pre>\n\n<p>Then all of the test methods that test the API in the abstract class are run automatically.</p>\n"
},
{
"answer_id": 512707,
"author": "Thomas Dufour",
"author_id": 371593,
"author_profile": "https://Stackoverflow.com/users/371593",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, here is a quick mock-up of how JUnit 4 runs parameterized tests, but done in JUnit 3.8.2.</p>\n\n<p>Basically I'm subclassing and badly hijacking the TestSuite class to populate the list of tests according to the cross-product of testMethods and parameters. </p>\n\n<p>Unfortunately I've had to copy a couple of helper methods from TestSuite itself, and a few details are not perfect, such as the names of the tests in the IDE being the same across parameter sets (JUnit 4.x appends <code>[0]</code>, <code>[1]</code>, ...).</p>\n\n<p>Nevertheless, this seems to run fine in the text and AWT <code>TestRunner</code>s that ship with JUnit as well as in Eclipse.</p>\n\n<p>Here is the ParameterizedTestSuite, and further down a (silly) example of a parameterized test using it.</p>\n\n<p>(final note : I've written this with Java 5 in mind, it <em>should</em> be trivial to adapt to 1.4 if needed)</p>\n\n<p><em>ParameterizedTestSuite.java:</em></p>\n\n<pre><code>package junit.parameterized;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\npublic class ParameterizedTestSuite extends TestSuite {\n\n public ParameterizedTestSuite(\n final Class<? extends TestCase> testCaseClass,\n final Collection<Object[]> parameters) {\n\n setName(testCaseClass.getName());\n\n final Constructor<?>[] constructors = testCaseClass.getConstructors();\n if (constructors.length != 1) {\n addTest(warning(testCaseClass.getName()\n + \" must have a single public constructor.\"));\n return;\n }\n\n final Collection<String> names = getTestMethods(testCaseClass);\n\n final Constructor<?> constructor = constructors[0];\n final Collection<TestCase> testCaseInstances = new ArrayList<TestCase>();\n try {\n for (final Object[] objects : parameters) {\n for (final String name : names) {\n TestCase testCase = (TestCase) constructor.newInstance(objects);\n testCase.setName(name);\n testCaseInstances.add(testCase);\n }\n }\n } catch (IllegalArgumentException e) {\n addConstructionException(e);\n return;\n } catch (InstantiationException e) {\n addConstructionException(e);\n return;\n } catch (IllegalAccessException e) {\n addConstructionException(e);\n return;\n } catch (InvocationTargetException e) {\n addConstructionException(e);\n return;\n }\n\n\n for (final TestCase testCase : testCaseInstances) {\n addTest(testCase);\n } \n }\n private Collection<String> getTestMethods(\n final Class<? extends TestCase> testCaseClass) {\n Class<?> superClass= testCaseClass;\n final Collection<String> names= new ArrayList<String>();\n while (Test.class.isAssignableFrom(superClass)) {\n Method[] methods= superClass.getDeclaredMethods();\n for (int i= 0; i < methods.length; i++) {\n addTestMethod(methods[i], names, testCaseClass);\n }\n superClass = superClass.getSuperclass();\n }\n return names;\n }\n private void addTestMethod(Method m, Collection<String> names, Class<?> theClass) {\n String name= m.getName();\n if (names.contains(name))\n return;\n if (! isPublicTestMethod(m)) {\n if (isTestMethod(m))\n addTest(warning(\"Test method isn't public: \"+m.getName()));\n return;\n }\n names.add(name);\n }\n\n private boolean isPublicTestMethod(Method m) {\n return isTestMethod(m) && Modifier.isPublic(m.getModifiers());\n }\n\n private boolean isTestMethod(Method m) {\n String name= m.getName();\n Class<?>[] parameters= m.getParameterTypes();\n Class<?> returnType= m.getReturnType();\n return parameters.length == 0 && name.startsWith(\"test\") && returnType.equals(Void.TYPE);\n }\n\n private void addConstructionException(Exception e) {\n addTest(warning(\"Instantiation of a testCase failed \"\n + e.getClass().getName() + \" \" + e.getMessage()));\n }\n\n}\n</code></pre>\n\n<p><em>ParameterizedTest.java:</em></p>\n\n<pre><code>package junit.parameterized;\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.parameterized.ParameterizedTestSuite;\n\n\npublic class ParameterizedTest extends TestCase {\n\n private final int value;\n private int evilState;\n\n public static Collection<Object[]> parameters() {\n return Arrays.asList(\n new Object[] { 1 },\n new Object[] { 2 },\n new Object[] { -2 }\n );\n }\n\n public ParameterizedTest(final int value) {\n this.value = value;\n }\n\n public void testMathPow() {\n final int square = value * value;\n final int powSquare = (int) Math.pow(value, 2) + evilState;\n assertEquals(square, powSquare);\n evilState++;\n }\n\n public void testIntDiv() {\n final int div = value / value;\n assertEquals(1, div);\n }\n\n public static Test suite() {\n return new ParameterizedTestSuite(ParameterizedTest.class, parameters());\n }\n}\n</code></pre>\n\n<p>Note: the <code>evilState</code> variable is just here to show that all test instances are different as they should be, and that there is no shared state between them.</p>\n"
},
{
"answer_id": 5063336,
"author": "user626150",
"author_id": 626150,
"author_profile": "https://Stackoverflow.com/users/626150",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>a few details are not perfect, such as the names of the tests in the IDE being the same across parameter sets (JUnit 4.x appends [0], [1], ...).</p>\n</blockquote>\n\n<p>To solve this you just need to overwrite getName() and change the constructor in your test case class:</p>\n\n<pre><code> private String displayName;\n\n public ParameterizedTest(final int value) {\n this.value = value;\n this.displayName = Integer.toString(value);\n }\n\n @Override\n public String getName() {\n return super.getName() + \"[\" + displayName + \"]\";\n }\n</code></pre>\n"
},
{
"answer_id": 26492929,
"author": "Daniel Lubarov",
"author_id": 714009,
"author_profile": "https://Stackoverflow.com/users/714009",
"pm_score": 1,
"selected": false,
"text": "<p>For Android projects, we wrote a library called <a href=\"https://github.com/square/burst\" rel=\"nofollow\">Burst</a> for test parameterization. For example</p>\n\n<pre><code>public class ParameterizedTest extends TestCase {\n enum Drink { COKE, PEPSI, RC_COLA }\n\n private final Drink drink;\n\n // Nullary constructor required by Android test framework\n public ConstructorTest() {\n this(null);\n }\n\n public ConstructorTest(Drink drink) {\n this.drink = drink;\n }\n\n public void testSomething() {\n assertNotNull(drink);\n }\n}\n</code></pre>\n\n<p>Not really an answer to your question since you're not using Android, but a lot of projects which still use JUnit 3 do so because Android's test framework requires it, so I hope some other readers will find this helpful.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13051/"
] |
I have a JUnit 3.x TestCase which I would like to be able to parameterize. I'd like to parametrize the entire `TestCase` (including the fixture). However, the `TestSuite.addTestSuite()` method does not allow be to pass a `TestCase` object, just a class:
```
TestSuite suite = new TestSuite("suite");
suite.addTestSuite(MyTestCase.class);
```
I would like to be able to pass a parameter (a string) to the MyTestCase instance which is created when the test runs. As it is now, I have to have a separate class for each parameter value.
I tried passing it an anynomous subclass:
```
MyTestCase testCase = new MyTestCase() {
String getOption() {
return "some value";
}
}
suite.addTestSuite(testCase.getClass());
```
However, this fails with the assertion:
```
... MyTestSuite$1 has no public constructor TestCase(String name) or TestCase()`
```
Any ideas? Am I attacking the problem the wrong way?
|
If this is Java 5 or higher, you might want to consider switching to JUnit 4, which has support for parameterized test cases built in.
|
197,375 |
<p>I only just recently discovered that Visual C++ 2008 (and perhaps earlier versions as well?) supports <code>for each</code> syntax on stl lists et al to facilitate iteration.
For example:</p>
<pre><code>list<Object> myList;
for each (Object o in myList)
{
o.foo();
}
</code></pre>
<p>I was very happy to discover it, but I'm concerned about portability for the dreaded day when someone decides I need to be able to compile my code in say, gcc or some other compiler. Is this syntax widely supported and can I use it without worrying about portability issues?</p>
|
[
{
"answer_id": 197382,
"author": "Peter Kühne",
"author_id": 27351,
"author_profile": "https://Stackoverflow.com/users/27351",
"pm_score": 6,
"selected": true,
"text": "<p>For each is not standard C or C++ syntax. If you want to be able to compile this code in gcc or g++, you will need to create an iterator and use a standard for loop.</p>\n\n<p>QuantumPete</p>\n\n<p>[edit]\nThis seems to be a new feature introduced into MS Visual C++, so this is definitely not portable. Ref: <a href=\"http://msdn.microsoft.com/en-us/library/xey702bw%28VS.80%29.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/xey702bw%28VS.80%29.aspx</a> [/edit]</p>\n"
},
{
"answer_id": 197406,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 2,
"selected": false,
"text": "<p>The Boost Library has a portable <a href=\"http://engineering.meta-comm.com/resources/cs-win32_metacomm/doc/html/foreach.html\" rel=\"nofollow noreferrer\">ForEach imlementation</a>.</p>\n"
},
{
"answer_id": 197412,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>There is a very good portable alternative: <a href=\"http://engineering.meta-comm.com/resources/cs-win32_metacomm/doc/html/foreach.html\" rel=\"nofollow noreferrer\">Boost.Foreach</a>. Just dump this header into your project and you can write your loops as follows:</p>\n\n<pre><code>list<Object> myList;\n\nBOOST_FOREACH(Object o, myList)\n o.foo();\n</code></pre>\n"
},
{
"answer_id": 197429,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 3,
"selected": false,
"text": "<p>Visual C++ \"for each\" is not standard C++, meaning you won't be able to compile your code on other compilers such as g++. However, the STL proposes <a href=\"http://www.sgi.com/tech/stl/for_each.html\" rel=\"nofollow noreferrer\">std::for_each</a>, but its syntax is a lot less intuitive. Here is its prototype:</p>\n\n<pre><code>template <class InputIterator, class UnaryFunction>\nUnaryFunction for_each(InputIterator first, InputIterator last, UnaryFunction f);\n</code></pre>\n\n<p>It takes two iterators defining a valid range, and applies the unary function (or functor) f to each object in this range.\nYou can rewrite your example using std::for_each like this:</p>\n\n<pre><code>void foo(Object o)\n{\n o.foo();\n}\n...\nlist<Object> myList;\n\nstd::for_each(myList.begin(), myList.end(), foo);\n</code></pre>\n\n<p>However, if you want to stay close to the classical syntax of the for each construct, and if you're ok about using Boost, you can use <a href=\"http://engineering.meta-comm.com/resources/cs-win32_metacomm/doc/html/foreach.html\" rel=\"nofollow noreferrer\">BOOST.FOREACH</a>, which will let you write</p>\n\n<pre><code>list<Object> myList;\n\nBOOST_FOREACH(Object o, myList)\n{\n o.foo();\n}\n</code></pre>\n"
},
{
"answer_id": 197604,
"author": "argatxa",
"author_id": 23460,
"author_profile": "https://Stackoverflow.com/users/23460",
"pm_score": -1,
"selected": false,
"text": "<p>My vote goes for Luc, </p>\n\n<p>Stick to the standard STL algorithms and you will be better off by far. STL algorithms can make your life very easy, efficient and safe. Take a look at the off the shelve algorithms like find_if, count, count_if, sort, transform, etc... </p>\n\n<p>Point 5 onwards... \n<a href=\"http://www.sgi.com/tech/stl/table_of_contents.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/table_of_contents.html</a></p>\n\n<p>Boost is cool, but if you are going to use it just for the FOR_EACH macro it is too much cumbersome regarding the development/build environment setup. </p>\n\n<p>use boost when standard c++ / stl cannot solve the problem in an 'easy' way. </p>\n"
},
{
"answer_id": 197646,
"author": "user21714",
"author_id": 21714,
"author_profile": "https://Stackoverflow.com/users/21714",
"pm_score": 0,
"selected": false,
"text": "<p>I also recommend BOOST_FOREACH. I usually create a macro along the lines of:</p>\n\n<pre><code>#define _foreach(x,y) BOOST_FOREACH(x,y)\n</code></pre>\n\n<p>This tends to increase readability. You have to be careful about collisions with other foreach implementations though. For instance, Qt provides a 'foreach' and there's the std::for_each.</p>\n\n<p>I find that the std::for_each doesn't actually save much time since you end up making lots of one-off function objects to supply to the for_each call. It's usually just as fast to make standard for-loop using STL iterators. </p>\n"
},
{
"answer_id": 197755,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": false,
"text": "<p>I wouldn't use that. While it's a tempting feature, the syntax is incompatible with the upcoming C++0x standard, which uses:</p>\n\n<pre><code>list<Object> myList;\n\nfor (Object o : myList)\n{\n o.foo();\n}\n</code></pre>\n\n<p>to do the same thing.</p>\n"
},
{
"answer_id": 197926,
"author": "Mike Hordecki",
"author_id": 19082,
"author_profile": "https://Stackoverflow.com/users/19082",
"pm_score": 3,
"selected": false,
"text": "<p>If you'd like to use foreach and in the same time you don't want to add additional dependency (such as Boost) - this macro will help you:</p>\n\n<pre><code>#define VAR(V,init) __typeof(init) V=(init)\n#define FOREACH(I,C) for(VAR(I,(C).begin());I!=(C).end();I++)\n\nstd::vector<int> numbers;\n\nFOREACH(I, numbers)\n{\n std::cout << *I << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 8714582,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is indeed not portable. </p>\n\n<p>The following works with the C++ 0x standard and Visual C++ 2010 (which doesn't support the new \"ranged for\" syntax as far as I can tell).</p>\n\n<pre><code>#define for_each(_ITER_, _COLL_) for (auto _ITER_ = _COLL_.begin(); \\\n _ITER_ != _COLL_.end(); _ITER_++)\n</code></pre>\n\n<p>Now you can write:</p>\n\n<pre><code>list<Object> myList;\n\nfor_each (o, myList)\n{\n o.foo();\n}\n</code></pre>\n\n<p>Compare this to the BOOST_FOREACH macro code at <a href=\"http://www.boost.org/doc/libs/1_48_0/boost/foreach.hpp\" rel=\"nofollow\">http://www.boost.org/doc/libs/1_48_0/boost/foreach.hpp</a> which is not only complex it also has a number of dependencies on other boost libraries. </p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25731/"
] |
I only just recently discovered that Visual C++ 2008 (and perhaps earlier versions as well?) supports `for each` syntax on stl lists et al to facilitate iteration.
For example:
```
list<Object> myList;
for each (Object o in myList)
{
o.foo();
}
```
I was very happy to discover it, but I'm concerned about portability for the dreaded day when someone decides I need to be able to compile my code in say, gcc or some other compiler. Is this syntax widely supported and can I use it without worrying about portability issues?
|
For each is not standard C or C++ syntax. If you want to be able to compile this code in gcc or g++, you will need to create an iterator and use a standard for loop.
QuantumPete
[edit]
This seems to be a new feature introduced into MS Visual C++, so this is definitely not portable. Ref: <http://msdn.microsoft.com/en-us/library/xey702bw%28VS.80%29.aspx> [/edit]
|
197,379 |
<p>I am looking to create symlinks (soft links) from Java on a Windows Vista/ 2008 machine. I'm happy with the idea that I need to call out to the JNI to do this. I am after help on the actual C code though. What is the appropriate system call to create the link? Pointers to some good documentation on this subject would be very much appreciated.</p>
|
[
{
"answer_id": 197386,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 2,
"selected": false,
"text": "<p>Couldn't you just call out to the command line and use <strong>mklink</strong>?</p>\n"
},
{
"answer_id": 197420,
"author": "Scott James",
"author_id": 6715,
"author_profile": "https://Stackoverflow.com/users/6715",
"pm_score": 2,
"selected": false,
"text": "<p>This has been on my list to try, from my notes:</p>\n\n<p>The API:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa363866(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa363866(VS.85).aspx</a></p>\n\n<pre><code>BOOLEAN WINAPI CreateSymbolicLink(\n __in LPTSTR lpSymlinkFileName,\n __in LPTSTR lpTargetFileName,\n __in DWORD dwFlags\n);\n</code></pre>\n\n<p>Some C# examples:</p>\n\n<p><a href=\"http://community.bartdesmet.net/blogs/bart/archive/2006/10/24/Windows-Vista-_2D00_-Creating-symbolic-links-with-C_2300_.aspx\" rel=\"nofollow noreferrer\">http://community.bartdesmet.net/blogs/bart/archive/2006/10/24/Windows-Vista-<em>2D00</em>-Creating-symbolic-links-with-C_2300_.aspx</a></p>\n\n<p>A C++ Example, this is cnp from another article I was reading. I have not tested it so use it with caution.</p>\n\n<pre><code>typedef BOOL (WINAPI* CreateSymbolicLinkProc) (LPCSTR, LPCSTR, DWORD);\n\nvoid main(int argc, char *argv[]) \n{\n HMODULE h;\n CreateSymbolicLinkProc CreateSymbolicLink_func;\n LPCSTR link = argv[1];\n LPCSTR target = argv[2];\n DWORD flags = 0;\n\n h = LoadLibrary(\"kernel32\");\n CreateSymbolicLink_func =\n (CreateSymbolicLinkProc)GetProcAddress(h,\n if (CreateSymbolicLink_func == NULL) \n {\n fprintf(stderr, \"CreateSymbolicLinkA not available\\n\");\n } else \n {\n if ((*CreateSymbolicLink_func)(link, target, flags) == 0) \n {\n fprintf(stderr, \"CreateSymbolicLink failed: %d\\n\",\n GetLastError());\n\n } else \n {\n printf(\"Symbolic link created.\");\n }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>Having said this, I would not use this code :-) I would either be inclined to fork mklink or look at the native library from jruby/jpython (Sorry I cant look it up atm as my network connection is flakey). I seem to recall that jruby has written a library that wraps up various posix apis into java (thinks like chown that are required for ruby compliance but are not cross platform). This library is being used by the jpython folks who seem very pleased with it. I would be surprised if this library does not offer sym link support.</p>\n"
},
{
"answer_id": 197440,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 4,
"selected": true,
"text": "<p>Symbolic links in Windows are created using the <a href=\"http://msdn.microsoft.com/en-us/library/aa363866.aspx\" rel=\"noreferrer\">CreateSymbolicLink API Function</a>, which takes parameters very similar to the command line arguments accepted by <a href=\"http://technet.microsoft.com/en-us/library/cc753194.aspx\" rel=\"noreferrer\">the Mklink command line utility</a>.</p>\n\n<p>Assuming you're correctly referencing the JNI and Win32 SDK headers, your code could thus be as simple as:</p>\n\n<pre><code>JNIEXPORT jboolean JNICALL Java_ClassName_MethodName\n (JNIEnv *env, jstring symLinkName, jstring targetName)\n{\n const char *nativeSymLinkName = env->GetStringUTFChars(symLinkName, 0);\n const char *nativeTargetName = env->GetStringUTFChars(targetName, 0);\n\n jboolean success = (CreateSymbolicLink(nativeSymLinkName, nativeTargetName, 0) != 0);\n\n env->ReleaseStringUTFChars(symLinkName, nativeSymLinkName);\n env->ReleaseStringUTFChars(targetName, nativeTargetName);\n\n return success;\n}\n</code></pre>\n\n<p>Note that this is just off the top of my head, and I haven't dealt with JNI in ages, so I may have overlooked some of the finer points of making this work...</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7122/"
] |
I am looking to create symlinks (soft links) from Java on a Windows Vista/ 2008 machine. I'm happy with the idea that I need to call out to the JNI to do this. I am after help on the actual C code though. What is the appropriate system call to create the link? Pointers to some good documentation on this subject would be very much appreciated.
|
Symbolic links in Windows are created using the [CreateSymbolicLink API Function](http://msdn.microsoft.com/en-us/library/aa363866.aspx), which takes parameters very similar to the command line arguments accepted by [the Mklink command line utility](http://technet.microsoft.com/en-us/library/cc753194.aspx).
Assuming you're correctly referencing the JNI and Win32 SDK headers, your code could thus be as simple as:
```
JNIEXPORT jboolean JNICALL Java_ClassName_MethodName
(JNIEnv *env, jstring symLinkName, jstring targetName)
{
const char *nativeSymLinkName = env->GetStringUTFChars(symLinkName, 0);
const char *nativeTargetName = env->GetStringUTFChars(targetName, 0);
jboolean success = (CreateSymbolicLink(nativeSymLinkName, nativeTargetName, 0) != 0);
env->ReleaseStringUTFChars(symLinkName, nativeSymLinkName);
env->ReleaseStringUTFChars(targetName, nativeTargetName);
return success;
}
```
Note that this is just off the top of my head, and I haven't dealt with JNI in ages, so I may have overlooked some of the finer points of making this work...
|
197,381 |
<p>I am dealing with MySQL tables that are essentially results of raytracing simulations on a simulated office room with a single venetian blind. I usually need to retrieve the simulation's result for a unique combination of time and blind's settings. So I end up doing a lot of</p>
<pre><code>SELECT result FROM results WHERE timestamp='2005-05-05 12:30:25' \
AND opening=40 AND slatangle=60
</code></pre>
<p>This looks suspiciously optimizable, since this query should never ever return more than one row. Does it make sense to define an index on the three columns that uniquely identify each row? Or are there other techniques I can use?</p>
|
[
{
"answer_id": 197408,
"author": "mlarsen",
"author_id": 17700,
"author_profile": "https://Stackoverflow.com/users/17700",
"pm_score": 3,
"selected": true,
"text": "<p>The answer is most definately a yes. If you define a unique index on timestamp, opening and slatangle MySQL should be able to find your row with very few disc seeks.</p>\n\n<p>You might experiment with creating an index on timestamp, opening, slateangle and result. MySQL may be able to fetch your data from the index without touching the datafile at all.</p>\n\n<p>The MySQL Manual has a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/query-speed.html\" rel=\"nofollow noreferrer\">section about optimzing queries</a>. </p>\n"
},
{
"answer_id": 197417,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I wouldn't suggest adding 3 indexes. An index using all three columns may be better and even setting the primary key unique on that combination would be best - only if you're sure that it unique.</p>\n"
},
{
"answer_id": 211275,
"author": "William Macdonald",
"author_id": 2725,
"author_profile": "https://Stackoverflow.com/users/2725",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest adding\n LIMIT 1;\nto the end of the query.</p>\n\n<p>William</p>\n"
},
{
"answer_id": 600188,
"author": "Joe Kuan",
"author_id": 72498,
"author_profile": "https://Stackoverflow.com/users/72498",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, create an index of multiple columns helps. Also you should test the performance of different column order, ie <em>O(c1, c2, c3) != O(c2, c1, c3)</em></p>\n\n<p>Have a look</p>\n\n<p><a href=\"http://joekuan.wordpress.com/2009/01/23/mysql-optimize-your-query-to-be-more-scalable-part-12/\" rel=\"nofollow noreferrer\">http://joekuan.wordpress.com/2009/01/23/mysql-optimize-your-query-to-be-more-scalable-part-12/</a>\n<a href=\"http://joekuan.wordpress.com/2009/01/23/mysql-optimize-your-query-to-be-more-scalable-part-22/\" rel=\"nofollow noreferrer\">http://joekuan.wordpress.com/2009/01/23/mysql-optimize-your-query-to-be-more-scalable-part-22/</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428/"
] |
I am dealing with MySQL tables that are essentially results of raytracing simulations on a simulated office room with a single venetian blind. I usually need to retrieve the simulation's result for a unique combination of time and blind's settings. So I end up doing a lot of
```
SELECT result FROM results WHERE timestamp='2005-05-05 12:30:25' \
AND opening=40 AND slatangle=60
```
This looks suspiciously optimizable, since this query should never ever return more than one row. Does it make sense to define an index on the three columns that uniquely identify each row? Or are there other techniques I can use?
|
The answer is most definately a yes. If you define a unique index on timestamp, opening and slatangle MySQL should be able to find your row with very few disc seeks.
You might experiment with creating an index on timestamp, opening, slateangle and result. MySQL may be able to fetch your data from the index without touching the datafile at all.
The MySQL Manual has a [section about optimzing queries](http://dev.mysql.com/doc/refman/5.0/en/query-speed.html).
|
197,383 |
<p>I want to create a bundle from an arbitrary bundle identifier<br>
e.g. <code>com.apple.iokit.IOStorageFamily</code> </p>
<p>It's not an unreasonable thing to do as bundle IDs are supposed<br>
to be unique, however the obvious code does not work:</p>
<pre><code>NSString* bID = @"com.apple.iokit.IOStorageFamily";
NSBundle* bundle = [NSBundle bundleWithIdentifier:bID];
</code></pre>
<p>This code only works for bundles you've already loaded<br>
(hello, chicken and egg problem), and in fact, you have<br>
to know a little more than you'd like about the the identifier<br>
before you can do anything. For the above style of ID<br>
I grep out the final component and tranform it into<br>
<code>/System/Library/Extensions/IOStorageFamily.kext</code><br>
which I then load by path. </p>
<p>Is this the state of the art or is there a more general way? </p>
|
[
{
"answer_id": 198195,
"author": "Dave Verwer",
"author_id": 4496,
"author_profile": "https://Stackoverflow.com/users/4496",
"pm_score": 3,
"selected": false,
"text": "<p>Use this</p>\n\n<pre><code>NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@\"com.apple.TextEdit\"];\n</code></pre>\n"
},
{
"answer_id": 199171,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If what you're looking for is definitely a kext, then you could look at the info dictionary for each bundle in the /S/L/Es/ folder until you find yours. There's no search for bundle by identifier apart from for Applications (where LaunchServices will do it), and loaded bundles as you've already found.</p>\n"
},
{
"answer_id": 260466,
"author": "Nik Gervae",
"author_id": 33828,
"author_profile": "https://Stackoverflow.com/users/33828",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think Mac OS X keeps a global database of all bundle IDs everywhere.</p>\n\n<p>As noted, you can find an application in a pretty straightforward way with NSWorkspace.</p>\n\n<p>Also, since you used a kext for your example, on Leopard (10.5) there's a tool called \"kextfind\" that you can run to search for kexts in the system Exensions folder (kexts in other places won't be found unless you point the tool at those other places). kextfind has lots of options--see the man page for details--but to find a kext by bundle ID you can do this:</p>\n\n<pre><code>kextfind -bundle-id com.apple.iokit.IOStorageFamily\n</code></pre>\n\n<p>We don't currently have a C-level API for looking up kexts by bundle ID.</p>\n\n<p>As for hacking the path from the last component of the bundle ID: don't do that. There's nothing requiring the wrapper name to match the last component of the bundle ID, and I have seen kexts (to say nothing of other bundles), where the two do not match.</p>\n"
},
{
"answer_id": 260481,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 0,
"selected": false,
"text": "<p>In order to answer this question, I think one really needs to know \"Why are you looking bundle identifiers in this way?\" If there are always kexts you can search in some fairly reasonable places, if they are apps you can use LS, I don't see a case in which you would want to do both, so I don't see a need to have a common way to do it.</p>\n\n<p>It should be noted that you can have multiple instances of identical bundle identifiers on a Volume.</p>\n"
},
{
"answer_id": 1583143,
"author": "Georg Schölly",
"author_id": 24587,
"author_profile": "https://Stackoverflow.com/users/24587",
"pm_score": 3,
"selected": true,
"text": "<p>Just recently <a href=\"http://lists.apple.com/archives/darwin-dev/2009/Oct/msg00088.html\" rel=\"nofollow noreferrer\">Andrew Myrick answered a similar question</a> on the darwin-dev mailing list:</p>\n\n<blockquote>\n <p><code>KextManagerCreateURLForBundleIdentifier()</code>\n in <code><IOKit/kext/KextManager.h></code> may be\n of use, though I believe it only works\n for kexts that are either 1) loaded,\n or 2) in /S/L/E/. Here is the Snow\n Leopard headerdoc:</p>\n\n<pre><code>/*!\n * @function KextManagerCreateURLForBundleIdentifier\n * @abstract Create a URL locating a kext with a given bundle identifier.\n *\n * @param allocator\n * The allocator to use to allocate memory for the new object.\n * Pass <code>NULL</code> or <code>kCFAllocatorDefault</code>\n * to use the current default allocator.\n * @param kextIdentifier\n * The bundle identifier to look up.\n *\n * @result\n * A CFURLRef locating a kext with the requested bundle identifier.\n * Returns <code>NULL</code> if the kext cannot be found, or on error.\n *\n * @discussion\n * Kexts are looked up first by whether they are loaded, second by version.\n * Specifically, if <code>kextIdentifier</code> identifies a kext\n * that is currently loaded,\n * the returned URL will locate that kext if it's still present on disk.\n * If the requested kext is not loaded,\n * or if its bundle is not at the location it was originally loaded from,\n * the returned URL will locate the latest version of the desired kext,\n * if one can be found within the system extensions folder.\n * If no version of the kext can be found, <code>NULL</code> is returned.\n */\nCFURLRef KextManagerCreateURLForBundleIdentifier(\n CFAllocatorRef allocator,\n CFStringRef kextIdentifier);\n</code></pre>\n \n <p>Note that prior to Snow Leopard, it\n may only work for kexts in /S/L/E; the\n API existed, but there was no\n headerdoc describing its behavior.</p>\n</blockquote>\n\n<p>For me this worked really well on Mac OS X 10.5.</p>\n"
},
{
"answer_id": 10064287,
"author": "Pierre Lebeaupin",
"author_id": 80734,
"author_profile": "https://Stackoverflow.com/users/80734",
"pm_score": 0,
"selected": false,
"text": "<p>For completeness, I should mention you can search for all bundles (not just KEXTs) with a given bundle identifier using the <a href=\"https://developer.apple.com/library/mac/documentation/Carbon/Reference/MDItemRef/Reference/reference.html#//apple_ref/c/data/kMDItemCFBundleIdentifier\" rel=\"nofollow\"><code>kMDItemCFBundleIdentifier</code></a> Spotlight/metadata key; of course you have to be ready to handle there being more than one (normally they should have different versions).</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22147/"
] |
I want to create a bundle from an arbitrary bundle identifier
e.g. `com.apple.iokit.IOStorageFamily`
It's not an unreasonable thing to do as bundle IDs are supposed
to be unique, however the obvious code does not work:
```
NSString* bID = @"com.apple.iokit.IOStorageFamily";
NSBundle* bundle = [NSBundle bundleWithIdentifier:bID];
```
This code only works for bundles you've already loaded
(hello, chicken and egg problem), and in fact, you have
to know a little more than you'd like about the the identifier
before you can do anything. For the above style of ID
I grep out the final component and tranform it into
`/System/Library/Extensions/IOStorageFamily.kext`
which I then load by path.
Is this the state of the art or is there a more general way?
|
Just recently [Andrew Myrick answered a similar question](http://lists.apple.com/archives/darwin-dev/2009/Oct/msg00088.html) on the darwin-dev mailing list:
>
> `KextManagerCreateURLForBundleIdentifier()`
> in `<IOKit/kext/KextManager.h>` may be
> of use, though I believe it only works
> for kexts that are either 1) loaded,
> or 2) in /S/L/E/. Here is the Snow
> Leopard headerdoc:
>
>
>
> ```
> /*!
> * @function KextManagerCreateURLForBundleIdentifier
> * @abstract Create a URL locating a kext with a given bundle identifier.
> *
> * @param allocator
> * The allocator to use to allocate memory for the new object.
> * Pass <code>NULL</code> or <code>kCFAllocatorDefault</code>
> * to use the current default allocator.
> * @param kextIdentifier
> * The bundle identifier to look up.
> *
> * @result
> * A CFURLRef locating a kext with the requested bundle identifier.
> * Returns <code>NULL</code> if the kext cannot be found, or on error.
> *
> * @discussion
> * Kexts are looked up first by whether they are loaded, second by version.
> * Specifically, if <code>kextIdentifier</code> identifies a kext
> * that is currently loaded,
> * the returned URL will locate that kext if it's still present on disk.
> * If the requested kext is not loaded,
> * or if its bundle is not at the location it was originally loaded from,
> * the returned URL will locate the latest version of the desired kext,
> * if one can be found within the system extensions folder.
> * If no version of the kext can be found, <code>NULL</code> is returned.
> */
> CFURLRef KextManagerCreateURLForBundleIdentifier(
> CFAllocatorRef allocator,
> CFStringRef kextIdentifier);
>
> ```
>
> Note that prior to Snow Leopard, it
> may only work for kexts in /S/L/E; the
> API existed, but there was no
> headerdoc describing its behavior.
>
>
>
For me this worked really well on Mac OS X 10.5.
|
197,387 |
<p>Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion?</p>
<pre><code>class MyClass(object):
def my_function():
"""This docstring works!"""
return True
my_list = []
"""This docstring does not work!"""
</code></pre>
|
[
{
"answer_id": 197499,
"author": "codeape",
"author_id": 3571,
"author_profile": "https://Stackoverflow.com/users/3571",
"pm_score": 5,
"selected": true,
"text": "<p>To my knowledge, it is not possible to assign docstrings to module data members.</p>\n\n<p><a href=\"http://www.python.org/dev/peps/pep-0224/\" rel=\"noreferrer\">PEP 224</a> suggests this feature, but the PEP was rejected.</p>\n\n<p>I suggest you document the data members of a module in the module's docstring:</p>\n\n<pre><code># module.py:\n\"\"\"About the module.\n\nmodule.data: contains the word \"spam\"\n\n\"\"\"\n\ndata = \"spam\"\n</code></pre>\n"
},
{
"answer_id": 197566,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 4,
"selected": false,
"text": "<p>It <strong>is</strong> possible to make documentation of module's data, with use of <a href=\"http://epydoc.sourceforge.net/\" rel=\"noreferrer\">epydoc</a> syntax. Epydoc is one of the most frequently used documentation tools for Python.</p>\n\n<p>The syntax for documenting is <code>#:</code> above the variable initialization line, like this:</p>\n\n<pre><code># module.py:\n\n#: Very important data.\n#: Use with caution.\n#: @type: C{str}\ndata = \"important data\"\n</code></pre>\n\n<p>Now when you generate your documentation, <code>data</code> will be described as module variable with given description and type <code>str</code>. You can omit the <code>@type</code> line.</p>\n"
},
{
"answer_id": 199179,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<p>As codeape explains, it's not possible to document general data members.</p>\n\n<p>However, it <em>is</em> possible to document <code>property</code> data members:</p>\n\n<pre><code>class Foo:\n def get_foo(self): ...\n\n def set_foo(self, val): ...\n\n def del_foo(self): ...\n\n foo = property(get_foo, set_foo, del_foo, '''Doc string here''')\n</code></pre>\n\n<p>This will give a docstring to the <code>foo</code> attribute, obviously.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/985/"
] |
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion?
```
class MyClass(object):
def my_function():
"""This docstring works!"""
return True
my_list = []
"""This docstring does not work!"""
```
|
To my knowledge, it is not possible to assign docstrings to module data members.
[PEP 224](http://www.python.org/dev/peps/pep-0224/) suggests this feature, but the PEP was rejected.
I suggest you document the data members of a module in the module's docstring:
```
# module.py:
"""About the module.
module.data: contains the word "spam"
"""
data = "spam"
```
|
197,407 |
<p>I need to define a calculated member in MDX (this is SAS OLAP, but I'd appreciate answers from people who work with different OLAP implementations anyway).</p>
<p>The new measure's value should be calculated from an existing measure by applying an additional filter condition. I suppose it will be clearer with an example:</p>
<ul>
<li>Existing measure: "Total traffic"</li>
<li>Existing dimension: "Direction" ("In" or "Out")</li>
<li>I need to create a calculated member "Incoming traffic", which equals "Total traffic" with an additional filter (Direction = "In")</li>
</ul>
<p>The problem is that I don't know MDX and I'm on a very tight schedule (so sorry for a newbie question). The best I could come up with is:</p>
<pre><code>([Measures].[Total traffic], [Direction].[(All)].[In])
</code></pre>
<p>Which almost works, except for cells with specific direction:</p>
<p><img src="https://i.stack.imgur.com/z3BxZ.png" alt="example"></p>
<p>So it looks like the "intrinsic" filter on Direction is overridden with my own filter). I need an intersection of the "intrinsic" filter and my own. My gut feeling was that it has to do with Intersecting <code>[Direction].[(All)].[In]</code> with the intrinsic coords of the cell being evaluated, but it's hard to know what I need without first reading up on the subject :)</p>
<p><strong>[update]</strong> I ended up with </p>
<pre><code>IIF([Direction].currentMember = [Direction].[(All)].[Out],
0,
([Measures].[Total traffic], [Direction].[(All)].[In])
)
</code></pre>
<p>..but at least in SAS OLAP this causes extra queries to be performed (to calculate the value for [in]) to the underlying data set, so I didn't use it in the end.</p>
|
[
{
"answer_id": 200913,
"author": "Magnus Smith",
"author_id": 11461,
"author_profile": "https://Stackoverflow.com/users/11461",
"pm_score": 4,
"selected": true,
"text": "<p>To begin with, you can define a new calculated measure in your MDX, and tell it to use the value of another measure, but with a filter applied:</p>\n\n<pre><code>WITH MEMBER [Measures].[Incoming Traffic] AS\n'([Measures].[Total traffic], [Direction].[(All)].[In])'\n</code></pre>\n\n<p>Whenever you show the new measure on a report, it will behave as if it has a filter of 'Direction > In' on it, regardless of whether the Direction dimension is used at all.</p>\n\n<p>But in your case, you WANT the Direction dimension to take precendence when used....so things get a little messy. You will have to detect if this dimension is in use, and act accordingly:</p>\n\n<pre><code>WITH MEMBER [Measures].[Incoming Traffic] AS\n'IIF([Direction].currentMember = [Direction].[(All)].[Out],\n ([Measures].[Total traffic]),\n ([Measures].[Total traffic], [Directon].[(All)].[In])\n)'\n</code></pre>\n\n<p>To see if the Dimension is in use, we check if the current cell is using OUT. If so we can return Total Traffic as it is. If not, we can tell it to use IN in our tuple.</p>\n"
},
{
"answer_id": 4667374,
"author": "Manish",
"author_id": 572518,
"author_profile": "https://Stackoverflow.com/users/572518",
"pm_score": 1,
"selected": false,
"text": "<p>I think you should put a column in your Total Traffic fact table for IN/OUT indication & create a Dim table for the IN & Out values. You can then analyse your data based on IN & Out.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1026/"
] |
I need to define a calculated member in MDX (this is SAS OLAP, but I'd appreciate answers from people who work with different OLAP implementations anyway).
The new measure's value should be calculated from an existing measure by applying an additional filter condition. I suppose it will be clearer with an example:
* Existing measure: "Total traffic"
* Existing dimension: "Direction" ("In" or "Out")
* I need to create a calculated member "Incoming traffic", which equals "Total traffic" with an additional filter (Direction = "In")
The problem is that I don't know MDX and I'm on a very tight schedule (so sorry for a newbie question). The best I could come up with is:
```
([Measures].[Total traffic], [Direction].[(All)].[In])
```
Which almost works, except for cells with specific direction:

So it looks like the "intrinsic" filter on Direction is overridden with my own filter). I need an intersection of the "intrinsic" filter and my own. My gut feeling was that it has to do with Intersecting `[Direction].[(All)].[In]` with the intrinsic coords of the cell being evaluated, but it's hard to know what I need without first reading up on the subject :)
**[update]** I ended up with
```
IIF([Direction].currentMember = [Direction].[(All)].[Out],
0,
([Measures].[Total traffic], [Direction].[(All)].[In])
)
```
..but at least in SAS OLAP this causes extra queries to be performed (to calculate the value for [in]) to the underlying data set, so I didn't use it in the end.
|
To begin with, you can define a new calculated measure in your MDX, and tell it to use the value of another measure, but with a filter applied:
```
WITH MEMBER [Measures].[Incoming Traffic] AS
'([Measures].[Total traffic], [Direction].[(All)].[In])'
```
Whenever you show the new measure on a report, it will behave as if it has a filter of 'Direction > In' on it, regardless of whether the Direction dimension is used at all.
But in your case, you WANT the Direction dimension to take precendence when used....so things get a little messy. You will have to detect if this dimension is in use, and act accordingly:
```
WITH MEMBER [Measures].[Incoming Traffic] AS
'IIF([Direction].currentMember = [Direction].[(All)].[Out],
([Measures].[Total traffic]),
([Measures].[Total traffic], [Directon].[(All)].[In])
)'
```
To see if the Dimension is in use, we check if the current cell is using OUT. If so we can return Total Traffic as it is. If not, we can tell it to use IN in our tuple.
|
197,441 |
<p>I'm a new user of Matlab, can you please help:<br>
I have the following code in an .M file:</p>
<pre><code>function f = divrat(w, C)
S=sqrt(diag(diag(C)));
s=diag(S);
f=sqrt(w'*C*w)/(w'*s);
</code></pre>
<p>I have stored this file (divrat.M) in the normal Matlab path, and therefore I'm assuming that Matlab will read the function when it's starting and that this function therefore should be available to use.</p>
<p>However, when I type</p>
<pre><code>>> divrat(w, C)
</code></pre>
<p>I get the following error</p>
<blockquote>
<p>??? Undefined function or method 'divrat' for input arguments of type 'double'. </p>
</blockquote>
<p>What is the error message telling me to do, I can't see any error in the code or the function call?</p>
|
[
{
"answer_id": 197543,
"author": "hakan",
"author_id": 3993,
"author_profile": "https://Stackoverflow.com/users/3993",
"pm_score": 2,
"selected": false,
"text": "<p>The error code indicates the function definition cannot be found. Make sure you're calling the function from the same workspace as the <code>divrat.m</code> file is stored. And make sure <code>divrat</code> function is not a subfunction, it should be first function declaration in the file. You can also try to call the function from the same <code>divrat.m</code> file in order to see if the problem is with workspace selection or the function.</p>\n\n<p>By the way, why didn't you simply say </p>\n\n<pre><code>s = sqrt(diag(C));\n</code></pre>\n\n<p>Wouldn't it be the same?</p>\n"
},
{
"answer_id": 197605,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 2,
"selected": false,
"text": "<p>Also, name it <code>divrat.m</code>, not <code>divrat.M</code>. This shouldn't matter on most OSes, but who knows...</p>\n\n<p>You can also test whether matlab can find a function by using the <code>which</code> command, i.e. </p>\n\n<pre><code>which divrat\n</code></pre>\n"
},
{
"answer_id": 214278,
"author": "bastibe",
"author_id": 1034,
"author_profile": "https://Stackoverflow.com/users/1034",
"pm_score": 2,
"selected": false,
"text": "<p>The function itself is valid matlab-code. The problem must be something else.<br>\nTry calling the function from within the directory it is located or add that directory to your searchpath using <code>addpath('pathname')</code>.</p>\n"
},
{
"answer_id": 219406,
"author": "Sundar R",
"author_id": 8127,
"author_profile": "https://Stackoverflow.com/users/8127",
"pm_score": 3,
"selected": false,
"text": "<p>As others have pointed out, this is very probably a problem with the path of the function file not being in Matlab's 'path'. </p>\n\n<p>One easy way to verify this is to open your function in the Editor and press the <kbd>F5</kbd> key. This would make the Editor try to run the file, and in case the file is not in path, it will prompt you with a message box. Choose <code>Add to Path</code> in that, and you must be fine to go. </p>\n\n<p>One side note: at the end of the above process, Matlab command window will give an error saying arguments missing: obviously, we didn't provide any arguments when we tried to run from the editor. But from now on you can use the function from the command line giving the correct arguments.</p>\n"
},
{
"answer_id": 219445,
"author": "Marc",
"author_id": 8478,
"author_profile": "https://Stackoverflow.com/users/8478",
"pm_score": 2,
"selected": false,
"text": "<p>The most common cause of this problem is that Matlab cannot find the file on it's search path. Basically, Matlab looks for files in:<br></p>\n\n<ol>\n<li>The current directory (<code>pwd</code>);</li>\n<li>Directly in a directory on the path (to see the path, type <code>path</code> at the command line) </li>\n<li>In a directory named <code>@(whatever the class of the first argument is)</code> that is in any directory above.<br><br>\n<p>As someone else suggested, you can use the command <code>which</code>, but that is often unhelpful in this case - it tells you Matlab can't find the file, which you knew already.<br>\n<br>\nSo the first thing to do is make sure the file is locatable on the path.<br>\n<p>\nNext thing to do is make sure that the file that matlab is finding (use which) requires the same type as the first argument you are actually passing. I.el, If <code>w</code> is supposed to be different class, and there is a <code>divrat</code> function there, but <code>w</code> is actually empty, <code>[]</code>, so matlab is looking for <code>Double/divrat</code>, when there is only a <code>@(yourclass)/divrat.</code> This is just speculation on my part, but this often bites me.</li>\n</ol>\n"
},
{
"answer_id": 309136,
"author": "Todd",
"author_id": 30841,
"author_profile": "https://Stackoverflow.com/users/30841",
"pm_score": 5,
"selected": false,
"text": "<p>You get this error when the function isn't on the MATLAB path or in pwd.</p>\n\n<p>First, make sure that you are able to find the function using:</p>\n\n<pre><code>>> which divrat\nc:\\work\\divrat\\divrat.m\n</code></pre>\n\n<p>If it returns:</p>\n\n<pre><code>>> which divrat\n'divrat' not found.\n</code></pre>\n\n<p>It is not on the MATLAB path or in PWD.</p>\n\n<p>Second, make sure that the directory that contains <code>divrat</code> is on the MATLAB path using the <code>PATH</code> command. It may be that a directory that you thought was on the path isn't actually on the path.</p>\n\n<p>Finally, make sure you aren't using a \"private\" directory. If <code>divrat</code> is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:</p>\n\n<pre><code>>> foo\n\nans =\n\n 1\n\n>> divrat(1,1)\n??? Undefined function or method 'divrat' for input arguments of type 'double'.\n\n>> which -all divrat\nc:\\work\\divrat\\private\\divrat.m % Private to divrat\n</code></pre>\n"
},
{
"answer_id": 29729347,
"author": "user262",
"author_id": 2863327,
"author_profile": "https://Stackoverflow.com/users/2863327",
"pm_score": 0,
"selected": false,
"text": "<p>I am pretty sure that the reason why this problem happened is because of the license of the toolbox (package) in which this function belongs in. Write <code>which divrat</code> and see what will be the result. If it returns path of the function and the comment <code>Has no license available</code>, then the problem is related to the license. That means, license of the package is not set correctly. Mostly it happens if the package (toolbox) of this function is added later, i.e., after installation of the original <code>matlab</code>. Please check and solve the license issue, then it will work fine. </p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm a new user of Matlab, can you please help:
I have the following code in an .M file:
```
function f = divrat(w, C)
S=sqrt(diag(diag(C)));
s=diag(S);
f=sqrt(w'*C*w)/(w'*s);
```
I have stored this file (divrat.M) in the normal Matlab path, and therefore I'm assuming that Matlab will read the function when it's starting and that this function therefore should be available to use.
However, when I type
```
>> divrat(w, C)
```
I get the following error
>
> ??? Undefined function or method 'divrat' for input arguments of type 'double'.
>
>
>
What is the error message telling me to do, I can't see any error in the code or the function call?
|
You get this error when the function isn't on the MATLAB path or in pwd.
First, make sure that you are able to find the function using:
```
>> which divrat
c:\work\divrat\divrat.m
```
If it returns:
```
>> which divrat
'divrat' not found.
```
It is not on the MATLAB path or in PWD.
Second, make sure that the directory that contains `divrat` is on the MATLAB path using the `PATH` command. It may be that a directory that you thought was on the path isn't actually on the path.
Finally, make sure you aren't using a "private" directory. If `divrat` is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:
```
>> foo
ans =
1
>> divrat(1,1)
??? Undefined function or method 'divrat' for input arguments of type 'double'.
>> which -all divrat
c:\work\divrat\private\divrat.m % Private to divrat
```
|
197,444 |
<p>I'm using libcurl in a Win32 C++ application.</p>
<p>I have the curllib.vcproj project added to my solution and set my other projects to depend on it.</p>
<p>How do I build it with SSL support enabled?</p>
|
[
{
"answer_id": 199052,
"author": "sharkin",
"author_id": 7891,
"author_profile": "https://Stackoverflow.com/users/7891",
"pm_score": 7,
"selected": true,
"text": "<p>Well, since this post failed badly, I had to dig into the matter myself. </p>\n\n<p><strong><em>Also check out the other answers and comments for additional info regarding other versions etc.</em></strong></p>\n\n<p><strong>EDIT: Since I posted this Q there seems to be ready-built binaries made available from the curl homepage. Check out <a href=\"https://stackoverflow.com/questions/197444/building-libcurl-with-ssl-support-on-windows/5129202#5129202\">James' answer</a>.</strong></p>\n\n<h2>So here goes:</h2>\n\n<p>-</p>\n\n<p><strong>Preprocessor</strong></p>\n\n<p>The following two symbols need to be fed to the preprocessor to enable SSL for libcurl:</p>\n\n<pre><code>USE_SSLEAY\nUSE_OPENSSL\n</code></pre>\n\n<p>(libcurl uses OpenSSL for SSL support)</p>\n\n<p>Alternatively the symbols can be added directly to a file called setup.h in libcurl, but I'm not too happy about modifying code in 3rd party distributions unless I really have to.</p>\n\n<p>Rebuilding the libcurl library, I now got some errors about OpenSSL include files not being found. Naturally, since I haven't set up the OpenSSL distribution properly yet.</p>\n\n<p><strong>Compiling OpenSSL binaries</strong></p>\n\n<p>I downloaded the OpenSSL 0.9.8 source distribution and unpacked it.</p>\n\n<p>In the root of the source distribution there's a file called INSTALL.W32 which describes how to compile the OpenSSL binaries. The build chain requires perl, so I installed the latest version of ActivePerl.</p>\n\n<p>I had some trouble with the build, which might not be applicable to all systems, but I'll go through it here in case somebody experiences the same.</p>\n\n<p>According to INSTALL.W32:</p>\n\n<p>Run the following commandline tasks with current directory set to the source distribution root:</p>\n\n<pre><code>1> perl Configure VC-WIN32 --prefix=c:/some/openssl/dir\n</code></pre>\n\n<p>(Where \"c:/some/openssl/dir\" should be replaced by the dir where OpenSSL should be installed. Don't use spaces in this path. The compilation further ahead will fail in that case)</p>\n\n<pre><code>2> ms\\do_ms\n</code></pre>\n\n<p>For me this step was unsuccessful at first, since I lacked the environment variables OSVERSION and TARGETCPU. I set these to <em>5.1.2600</em> and <em>x86</em> respectively. You may get complaint about OSVERSION being \"insane\", but look closer, this error is for WinCE and doesn't affect the Win32 setup. To get hold of your OS version, run the 'ver' command from a command prompt or run winver.exe.</p>\n\n<pre><code>3> nmake -f ms\\nt.mak (for static library)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>3> nmake -f ms\\ntdll.mak (for DLL)\n</code></pre>\n\n<p>The source now compiles. Took approx 5 minutes on my laptop.</p>\n\n<p>When compilation is completed, the libs or binaries have been placed in:</p>\n\n<p><em>distroot/out32</em> - for static library build</p>\n\n<p>or</p>\n\n<p><em>distroot/out32dll</em> - for DLL build</p>\n\n<p><strong>Building and linking</strong></p>\n\n<p>Now, back to visual studio and point out the libs and include path for headers. The include files are located in <strong>distroot/inc32/openssl</strong>.</p>\n\n<p>Remember to add <em>libeay32.lib</em> and <em>ssleay32.lib</em> as linker input.</p>\n\n<p>Rebuild the libcurl project. </p>\n\n<p><strong>Error!</strong> </p>\n\n<p>Well at least for me with this version of OpenSSL. \nit complained about a struct typedef in one of the OpenSSL headers. I couldn't find any info on this. After an hour of googling I broke my own principle and commented out the typedef from the OpenSSL header, and luckily libcurl wasn't using that symbol so it built fine.</p>\n\n<p><em>Update: As pointed out by Jason, this issue seems to have dissapeared as of version 1.0.0a.</em></p>\n\n<p>Now, for confirming that SSL support is enabled for libcurl, run the following code:</p>\n\n<pre><code>curl_version_info_data * vinfo = curl_version_info( CURLVERSION_NOW );\nif( vinfo->features & CURL_VERSION_SSL )\n // SSL support enabled\nelse\n // No SSL\n</code></pre>\n\n<hr>\n\n<p>Simple as that.</p>\n"
},
{
"answer_id": 1397802,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>i did \"do_nt.bat\" for windows 7 rc7100\ndon't forget \"nmake -f ms\\nt.mak install\" to copy the headers correctly</p>\n\n<p>thanks this did help a lot</p>\n"
},
{
"answer_id": 2097530,
"author": "hemp",
"author_id": 51055,
"author_profile": "https://Stackoverflow.com/users/51055",
"pm_score": 1,
"selected": false,
"text": "<p>Couple of notes in response to and/or in addition to the above..</p>\n\n<p>First, if you don't want to mess with ActivePerl, <a href=\"http://win32.perl.org/wiki/index.php?title=Strawberry_Perl\" rel=\"nofollow noreferrer\">Strawberry Perl</a> is terrific and worked perfectly for this.</p>\n\n<p>Second, in lieu of using <strong>do_ms</strong>.bat, I would recommend preferring <strong>do_masm</strong> if possible since, according to INSTALL.W32, </p>\n\n<blockquote>\n <p>This is worth doing because it will\n result in faster code: for example it\n will typically result in a 2 times\n speedup in the RSA routines.</p>\n</blockquote>\n\n<p>Also, build <em>0.9.8l</em> (L) of OpenSSL was a nightmare so I eventually gave up and reverted to <em>0.9.8k</em> which built and linked (statically) with libcurl 1.9 without issue.</p>\n"
},
{
"answer_id": 2843535,
"author": "GaMer13",
"author_id": 193298,
"author_profile": "https://Stackoverflow.com/users/193298",
"pm_score": 3,
"selected": false,
"text": "<p>When compiling OpenSSL 1.0.0 on Windows with Visual Studio 2010, it eventually threw a 0x2 error:</p>\n<blockquote>\n<p>NMAKE : fatal error U1077: '"C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\n\\VC\\BIN\\cl.EXE"' : return code '0x2'</p>\n<p>Stop.</p>\n</blockquote>\n<p>It seems that this error will be thrown because of a flag in the perl Configure file, namely -WX.\nAs the MSDN documentation states:</p>\n<blockquote>\n<p>Treats all compiler warnings as errors. For a new project, it may be best to use /WX in all compilations; resolving all warnings will ensure the fewest possible hard-to-find code defects.</p>\n</blockquote>\n<p>After removing the -WX occurrences in the Configure file and re-entering the commands stated <a href=\"https://stackoverflow.com/questions/197444/building-libcurl-with-ssl-support-on-windows/199052#199052\">here</a> it built fine and passed all tests.</p>\n"
},
{
"answer_id": 5129202,
"author": "James",
"author_id": 623491,
"author_profile": "https://Stackoverflow.com/users/623491",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe this isn't the answer anyone is looking for, but I simply just downloaded the precompiled DLLs from <a href=\"http://www.gknw.net/mirror/curl/win32/curl-7.21.4-ssl-sspi-zlib-static-bin-w32.zip\" rel=\"nofollow noreferrer\">this link</a> found at <a href=\"http://curl.haxx.se/download.html\" rel=\"nofollow noreferrer\">http://curl.haxx.se/download.html</a></p>\n\n<p>I ran the test that sharkin provided, and <code>if( vinfo->features & CURL_VERSION_SSL )</code> proved to be true.</p>\n"
},
{
"answer_id": 9733793,
"author": "Hackle",
"author_id": 1273500,
"author_profile": "https://Stackoverflow.com/users/1273500",
"pm_score": 2,
"selected": false,
"text": "<p>If you build with Visual Studio IDE and get 58 odd warnings as the likes of </p>\n\n<p>\"inconsistent dll linkage curl_global_init / curl_msnprintf /...\"</p>\n\n<p>you should add CURL_STATICLIB to the preproccessor definitions.</p>\n\n<p>so the entire definition line should look like:</p>\n\n<p>USE_SSLEAY;USE_OPENSSL;CURL_STATICLIB.</p>\n\n<p>With this all the warning will disappear.</p>\n\n<p>Some would ignore the warnings and go on using the libs, but then will get corresponding *error*s as the likes of curl_global_init / curl_msnprintf. It can be very annoying.</p>\n\n<p>Hope it can help somebody.</p>\n"
},
{
"answer_id": 9750612,
"author": "jayaanand",
"author_id": 1275823,
"author_profile": "https://Stackoverflow.com/users/1275823",
"pm_score": 2,
"selected": false,
"text": "<pre><code>\\ fatal error C1083: Cannot open include\nfile: 'stdlib.h': No such file or directory\nNMAKE: fatal error U1077::return code \n</code></pre>\n\n<p>That error can be solved by executing vcvarsall.bat in Visual Studio.</p>\n"
},
{
"answer_id": 26273642,
"author": "fa.",
"author_id": 83375,
"author_profile": "https://Stackoverflow.com/users/83375",
"pm_score": 3,
"selected": false,
"text": "<p>Following Robert Oschler's advice, here is my comment on the question as answer :</p>\n\n<p>You can build recent libcurl (2012) with native SSL support for windows using the preprocessor symbols: USE_WINDOWS_SSPI and USE_SCHANNEL instead of the OpenSSL ones. </p>\n"
},
{
"answer_id": 47651867,
"author": "VincentTellier",
"author_id": 519376,
"author_profile": "https://Stackoverflow.com/users/519376",
"pm_score": 2,
"selected": false,
"text": "<p>In my case follow the curl README file was enough.<br>\nMy configuration is the following:</p>\n\n<ul>\n<li>Visual Studio 2015 (VC14)</li>\n<li>Static library</li>\n<li>Win64</li>\n<li>curl version 7.57.0</li>\n<li>OpenSSL 1.0.2</li>\n</ul>\n\n<h2>Compilation of libCurl</h2>\n\n<ol>\n<li>Download libcurl source there: <a href=\"https://curl.haxx.se/download.html\" rel=\"nofollow noreferrer\">https://curl.haxx.se/download.html</a></li>\n<li>Uncompress the file and go to the folder <code>curl-7.57.0\\projects</code></li>\n<li>Open the README file and follow the instructions, this lead me to do the following:\n\n<ul>\n<li>Downloaded <a href=\"https://www.openssl.org/source/\" rel=\"nofollow noreferrer\">OpenSSL</a></li>\n<li>Extract it and rename it to <code>openssl</code>, <strong>put it aside the curl folder</strong>, this is important as you'll open the VS project that expect to find openssl there.</li>\n<li>Install <a href=\"https://www.activestate.com/activeperl\" rel=\"nofollow noreferrer\">Perl</a></li>\n<li>Execute the utility <code>build-openssl.bat</code> to perform the compilation of openSSL. With my settings this became the following:<br>\n<code>.\\build-openssl.bat vc14 x64 release ..\\..\\openssl\\</code><br>\njust runs <code>.\\build-openssl.bat -help</code> to know more about the parameters.<br>\nAfter that you can see OpenSSL has been compiled as you got a new folder here: <code>openssl\\build\\Win64</code></li>\n</ul></li>\n<li>Open the Visual Studio project <code>curl-7.57.0\\projects\\Windows\\VC14\\curl-all.sln</code></li>\n<li>Be sure to set the visual studio project to the build configuration you need (<code>LIB Release - LIB OpenSSL</code> in my case)</li>\n<li>Build all</li>\n<li>The library is located at <code>curl-7.57.0\\build\\Win64\\VC14\\LIB Release - LIB OpenSSL\\libcurl.lib</code></li>\n</ol>\n\n<h1>Remarks</h1>\n\n<ul>\n<li>Don't forget to define the <code>CURL_STATICLIB</code> preprocessor in your own project</li>\n<li>With static library, you will have to links with the dependencies of libcurl, see <a href=\"https://stackoverflow.com/a/3419935/519376\">this answer</a></li>\n<li>You might not want to depend on <em>LDAP</em>, in that case you can disable it by setting the preprocessor <code>CURL_DISABLE_LDAP</code> <em>before</em> you compile libcurl.</li>\n</ul>\n"
},
{
"answer_id": 48700926,
"author": "Ari Seyhun",
"author_id": 4988637,
"author_profile": "https://Stackoverflow.com/users/4988637",
"pm_score": 2,
"selected": false,
"text": "<h1>How to build libcurl C/C++ with OpenSSL (SSL support) on Windows</h1>\n\n<ol>\n<li>Install libcurl</li>\n<li>Install OpenSSl</li>\n<li>Build libcurl with OpenSSL</li>\n</ol>\n\n<hr>\n\n<h2>Installing libcurl</h2>\n\n<p>Go to the <a href=\"https://curl.haxx.se/download.html\" rel=\"nofollow noreferrer\">download page of libcurl</a> and donwnload the ZIP file under <strong>Source Archives</strong>. <em>In my case it is called <a href=\"https://curl.haxx.se/download/curl-7.58.0.zip\" rel=\"nofollow noreferrer\"><code>curl-7.58.0.zip</code></a></em></p>\n\n<p>Extract the archive and open <code>projects/Windows/VC15/curl_all.sln</code> with Visual Studio.</p>\n\n<h2>Installing OpenSSL</h2>\n\n<p>Download the windows binary of OpenSSL. In my case, I downloaded the windows installer file <a href=\"https://slproweb.com/download/Win32OpenSSL-1_1_0g.exe\" rel=\"nofollow noreferrer\"><code>Win32 OpenSSL v1.1.0g</code></a> from the <a href=\"https://slproweb.com/products/Win32OpenSSL.html\" rel=\"nofollow noreferrer\">Shining Light Productions distribution</a>.</p>\n\n<p><em>The installation folder for me is <code>C:\\OpenSSL-Win32</code>.</em></p>\n\n<h2>Building libcurl with OpenSSL</h2>\n\n<p>In the <code>curl_all.sln</code> Visual Studio solution file, change the build configuration to <code>DLL Debug - DLL OpenSSL</code>.</p>\n\n<p>In the Solution Explorer, right click the project <code>curl</code> and go to Properties.</p>\n\n<p>Under <code>Linker -> General</code> modify <code>Additional Library Directories</code> and add the path to your <code>OpenSSL directory + \\lib</code>. In my case, this is <code>C:\\OpenSSL-Win32\\lib</code>.</p>\n\n<p>Apply and close the properties window.</p>\n\n<p>Right click the project <code>libcurl</code> and do the same as the previous step, add <code>OpenSSL directory + \\lib</code> to <code>Additional Library Directories</code> under <code>Linker -> General</code>.</p>\n\n<p>Under <code>C/C++ -> General</code>, add <code>C:\\OpenSSL-Win32\\include</code> to the <code>Additional Include Directories</code>.</p>\n\n<p>Finally go to <code>Linker -> Input</code> and modify <code>Additional Dependencies</code>. Replace all the lib files to the following:</p>\n\n<pre><code>ws2_32.lib\nwldap32.lib\nopenssl.lib\nlibssl.lib\nlibcrypto.lib\n</code></pre>\n\n<p>Apply and close the properties window.</p>\n\n<p>With the <code>DLL Debug - DLL OpenSSL</code> build configuration still selected, go to <code>Build -> Build Solution</code>.</p>\n\n<p>Copy the two dll files <code>libcrypto-1_1.dll</code> and <code>libssl-1_1.dll</code> from the OpenSSL bin directory <em>(<code>C:\\OpenSSL-Win32\\bin</code>)</em> to the just created build directory <code>curl-7.58.0\\build\\Win32\\VC15\\DLL Debug - DLL OpenSSL</code>.</p>\n\n<h2>Validating Build</h2>\n\n<p>Inside the build directory, run <code>curld.exe</code>. If it runs with no errors (missing dll, etc.) then your build was successful.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7891/"
] |
I'm using libcurl in a Win32 C++ application.
I have the curllib.vcproj project added to my solution and set my other projects to depend on it.
How do I build it with SSL support enabled?
|
Well, since this post failed badly, I had to dig into the matter myself.
***Also check out the other answers and comments for additional info regarding other versions etc.***
**EDIT: Since I posted this Q there seems to be ready-built binaries made available from the curl homepage. Check out [James' answer](https://stackoverflow.com/questions/197444/building-libcurl-with-ssl-support-on-windows/5129202#5129202).**
So here goes:
-------------
-
**Preprocessor**
The following two symbols need to be fed to the preprocessor to enable SSL for libcurl:
```
USE_SSLEAY
USE_OPENSSL
```
(libcurl uses OpenSSL for SSL support)
Alternatively the symbols can be added directly to a file called setup.h in libcurl, but I'm not too happy about modifying code in 3rd party distributions unless I really have to.
Rebuilding the libcurl library, I now got some errors about OpenSSL include files not being found. Naturally, since I haven't set up the OpenSSL distribution properly yet.
**Compiling OpenSSL binaries**
I downloaded the OpenSSL 0.9.8 source distribution and unpacked it.
In the root of the source distribution there's a file called INSTALL.W32 which describes how to compile the OpenSSL binaries. The build chain requires perl, so I installed the latest version of ActivePerl.
I had some trouble with the build, which might not be applicable to all systems, but I'll go through it here in case somebody experiences the same.
According to INSTALL.W32:
Run the following commandline tasks with current directory set to the source distribution root:
```
1> perl Configure VC-WIN32 --prefix=c:/some/openssl/dir
```
(Where "c:/some/openssl/dir" should be replaced by the dir where OpenSSL should be installed. Don't use spaces in this path. The compilation further ahead will fail in that case)
```
2> ms\do_ms
```
For me this step was unsuccessful at first, since I lacked the environment variables OSVERSION and TARGETCPU. I set these to *5.1.2600* and *x86* respectively. You may get complaint about OSVERSION being "insane", but look closer, this error is for WinCE and doesn't affect the Win32 setup. To get hold of your OS version, run the 'ver' command from a command prompt or run winver.exe.
```
3> nmake -f ms\nt.mak (for static library)
```
or
```
3> nmake -f ms\ntdll.mak (for DLL)
```
The source now compiles. Took approx 5 minutes on my laptop.
When compilation is completed, the libs or binaries have been placed in:
*distroot/out32* - for static library build
or
*distroot/out32dll* - for DLL build
**Building and linking**
Now, back to visual studio and point out the libs and include path for headers. The include files are located in **distroot/inc32/openssl**.
Remember to add *libeay32.lib* and *ssleay32.lib* as linker input.
Rebuild the libcurl project.
**Error!**
Well at least for me with this version of OpenSSL.
it complained about a struct typedef in one of the OpenSSL headers. I couldn't find any info on this. After an hour of googling I broke my own principle and commented out the typedef from the OpenSSL header, and luckily libcurl wasn't using that symbol so it built fine.
*Update: As pointed out by Jason, this issue seems to have dissapeared as of version 1.0.0a.*
Now, for confirming that SSL support is enabled for libcurl, run the following code:
```
curl_version_info_data * vinfo = curl_version_info( CURLVERSION_NOW );
if( vinfo->features & CURL_VERSION_SSL )
// SSL support enabled
else
// No SSL
```
---
Simple as that.
|
197,468 |
<p>I'm just starting up a new ATL/WTL project and I was wondering if the global _Module variable is still required? </p>
<p>Back a few years when I started working with WTL it was required (at least for ATL 3.0) that you define a global variable such as:</p>
<pre><code>CAppModule _Module;
</code></pre>
<p>To get ATL to work correctly. But recently I've read somewhere that this may not be required anymore (yet the wizard generated code still uses it). Also I did a search through the Visual C++ include directories and it only picked up _Module in a few places - most notably the ATL COM registry stuff.</p>
<p>So do I still need to define a global variable to use ATL these days?</p>
|
[
{
"answer_id": 200210,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 1,
"selected": false,
"text": "<p>In the sample projects of the latest WTL version, this is still used.</p>\n\n<p>In stdafx.h:</p>\n\n<pre><code>extern CAppModule _Module;\n</code></pre>\n\n<p>In implementation files:</p>\n\n<pre><code>CAppModule _Module;\n</code></pre>\n"
},
{
"answer_id": 253883,
"author": "Charles",
"author_id": 24898,
"author_profile": "https://Stackoverflow.com/users/24898",
"pm_score": 4,
"selected": true,
"text": "<p>Technically you do not need a global <code>_Module</code> instance since ATL/WTL version 7. Earlier ATL/WTL code referenced <code>_Module</code> by this specific name and expected you to declare a single instance of this object. This has since been replaced by a single instance object named <code>_AtlBaseModule</code> that is automatically declared for you in atlcore.h.</p>\n\n<p>Having said that, though, some of the best WTL features are contained within CAppModule and its base class CComModule. Automatic COM registration, message loop handling, etc. So most non-trivial WTL based apps will still want a singleton instance of a CComModule base class. However, it doesn't need to be named <code>_Module</code>.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3719/"
] |
I'm just starting up a new ATL/WTL project and I was wondering if the global \_Module variable is still required?
Back a few years when I started working with WTL it was required (at least for ATL 3.0) that you define a global variable such as:
```
CAppModule _Module;
```
To get ATL to work correctly. But recently I've read somewhere that this may not be required anymore (yet the wizard generated code still uses it). Also I did a search through the Visual C++ include directories and it only picked up \_Module in a few places - most notably the ATL COM registry stuff.
So do I still need to define a global variable to use ATL these days?
|
Technically you do not need a global `_Module` instance since ATL/WTL version 7. Earlier ATL/WTL code referenced `_Module` by this specific name and expected you to declare a single instance of this object. This has since been replaced by a single instance object named `_AtlBaseModule` that is automatically declared for you in atlcore.h.
Having said that, though, some of the best WTL features are contained within CAppModule and its base class CComModule. Automatic COM registration, message loop handling, etc. So most non-trivial WTL based apps will still want a singleton instance of a CComModule base class. However, it doesn't need to be named `_Module`.
|
197,482 |
<p>What are the guidelines for when to create a new exception type instead of using one of the built-in exceptions in .Net?</p>
<p>The problem that got me thinking is this. I have a WCF service, which is a basic input-output service. If the service is unable to create an output, because the input is invalid, I want to throw an exception, but which one?</p>
<p>Right now I'm just throwing system.Exception, but this doesn't feel right to me, I don't know why, it just feels wrong.
One thing that bugs me, if I test it with a unit test and I expect the system.Exception to be thrown. The exception could as well be thrown by the framework or other code and not by the code I excepted to throw. The test would then pass, as I get the expected exception, but it should have failed.</p>
<p>What do you recommend?</p>
|
[
{
"answer_id": 197488,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>Avoid throwing <code>System.Exception</code> or <code>System.ApplicationException</code> yourself, as they are too general.</p>\n\n<p>For WCF services there are Fault Contracts - a generic exception that you can tell subscibers to handle.</p>\n\n<p>Flag the interface with:</p>\n\n<pre><code>[FaultContract( typeof( LogInFault ) )]\nvoid LogIn( string userName, string password, bool auditLogin );\n</code></pre>\n\n<p>Then if there is an exception you can throw this specific fault:</p>\n\n<pre><code>throw new FaultException<LogInFault>( new LogInFault(), \"message\" );\n</code></pre>\n\n<p>Use the <code>[DataContract]</code> serialisation on your fault - this saves you from having to handle all the serialisation stuff exceptions normally require.</p>\n"
},
{
"answer_id": 197491,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Definitely avoid throwing System.Exception for anything other than throwaway code.</p>\n\n<p>If an argument to a method is invalid, throw <a href=\"http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx\" rel=\"noreferrer\">ArgumentException</a> (or some derived, more specific exception). Consult the docs for existing exceptions before creating your own - but it can often be useful to do so. (You can derive your own type of exception from ArgumentException, of course - if you've got some particular type of condition which you want to indicate from multiple places, creating a new type gives more information than just putting it in the error message.)</p>\n\n<p>Now error handling in WCF may well be different to error handling within the \"normal\" framework - I suggest you refer to WCF-specific docs/books for that.</p>\n"
},
{
"answer_id": 197494,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 0,
"selected": false,
"text": "<p>Always create a new exception type (or use a standard type if it suits you).</p>\n\n<p>In that case you can handle the exceptions as a group.</p>\n"
},
{
"answer_id": 197498,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "<p>It's not a good idea to throw System.Exception. The biggest reason for this is the effect it has on the calling code. How should they handle the exception? If the calling code is going to handle the exception, then they have to catch every exception, which is probably not the best thing for them to do.</p>\n\n<p>If a circumstance isn't covered by one of the standard exceptions, then you should create a new Exception object if the exception is something that calling code would be expected to handle as a special case.</p>\n"
},
{
"answer_id": 197502,
"author": "Fionn",
"author_id": 21566,
"author_profile": "https://Stackoverflow.com/users/21566",
"pm_score": 2,
"selected": false,
"text": "<p>System.Exception should only be used as a base class for Exceptions, never be thrown directly.</p>\n\n<p>The Framework offers already a lot of valid Exception classes like ArgumentException, ArgumentNullException, InvalidOperationException, FormatException, OverflowException, etc...</p>\n\n<p>You say you are doing I/O stuff, so a good idea is to look at similar operations in the framework (like int.Parse) and throw the same exceptions for similar errors.</p>\n\n<p>Or derive your own exception class from an existing exception class if none of them really fits your needs.</p>\n"
},
{
"answer_id": 197515,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>What are the guidelines for when to\n create a new exception type instead of\n using one of the built-in exceptions\n in .Net?</p>\n</blockquote>\n\n<p>When there is no suitable predefined exception class.<br>\n.NET FW is very rich, often you can find predefined exception.</p>\n\n<blockquote>\n <p>If the service is unable to create an\n output, because the input is invalid</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.argumentexception(VS.80).aspx\" rel=\"nofollow noreferrer\">ArgumentException Class (System)</a></p>\n\n<blockquote>\n <p>The exception that is thrown when one\n of the arguments provided to a method\n is not valid.</p>\n</blockquote>\n"
},
{
"answer_id": 197526,
"author": "Scott Lawrence",
"author_id": 3475,
"author_profile": "https://Stackoverflow.com/users/3475",
"pm_score": 0,
"selected": false,
"text": "<p>As previous posters have stated, you shouldn't be throwing System.Exception. In fact, if you ran FxCop on your code, it would flag that as a rule violation.</p>\n\n<p>I recommend having a look at Chapter 18 of Applied .NET Framework Programming, or chapter 19 of the more recent CLR via C# (2nd edition) for detailed guidance. Richter does an excellent job of correcting the misconceptions that a lot of developers hold about exceptions.</p>\n\n<p>Both books contain a list of the exceptions defined by the Framework Class Library. Look at the list and figure out the most specific exceptions possible that your code can throw. If you can recover from an exception, do so in that catch block. If you have need of multiple catch blocks, organize them from the most specific to the least specific. Create a custom exception if you can't find one in the existing list that suits the situation. </p>\n"
},
{
"answer_id": 197969,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 2,
"selected": false,
"text": "<p>If you throw System.Exception, then the caller must catch System.Exception. Both sides of this are a no-no, since it leaves us telling the user \"that didn't work\", rather than something more useful.</p>\n\n<p>An ArgumentException is useful if the caller passed in an invalid argument. If your function has an int parameter that you need to be an even number, then you would throw and ArgumentException telling the caller what parameter was invalid and why. However, if all arguments were valid but there is still a problem, you'll probably need a custom exception. This way the caller can tell the user excatly what went wrong.</p>\n\n<p>The test for me is really on the calling side. If I would have a dozen catches that all did the same thing, then I really only needed one exception. However, if I had one catch and would have a statement telling the user one of three things went wrong, then I really needed three unique exceptions.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44726/"
] |
What are the guidelines for when to create a new exception type instead of using one of the built-in exceptions in .Net?
The problem that got me thinking is this. I have a WCF service, which is a basic input-output service. If the service is unable to create an output, because the input is invalid, I want to throw an exception, but which one?
Right now I'm just throwing system.Exception, but this doesn't feel right to me, I don't know why, it just feels wrong.
One thing that bugs me, if I test it with a unit test and I expect the system.Exception to be thrown. The exception could as well be thrown by the framework or other code and not by the code I excepted to throw. The test would then pass, as I get the expected exception, but it should have failed.
What do you recommend?
|
Avoid throwing `System.Exception` or `System.ApplicationException` yourself, as they are too general.
For WCF services there are Fault Contracts - a generic exception that you can tell subscibers to handle.
Flag the interface with:
```
[FaultContract( typeof( LogInFault ) )]
void LogIn( string userName, string password, bool auditLogin );
```
Then if there is an exception you can throw this specific fault:
```
throw new FaultException<LogInFault>( new LogInFault(), "message" );
```
Use the `[DataContract]` serialisation on your fault - this saves you from having to handle all the serialisation stuff exceptions normally require.
|
197,489 |
<p>I am using the jQuery library to implement drag and drop. </p>
<p>How do I get at the element that is being dragged when it is dropped?</p>
<p>I want to get the id of the image inside the div. The following element is dragged:</p>
<pre><code><div class="block">
<asp:Image ID="Image9" AlternateText="10/12/2008 - Retina" Width=81 Height=84 ImageUrl="~/uploads/ImageModifier/retina.jpg" runat=server />
</div>
</code></pre>
<p>I have the standard dropped function from their example:</p>
<pre><code>$(".drop").droppable({
accept: ".block",
activeClass: 'droppable-active',
hoverClass: 'droppable-hover',
drop: function(ev, ui) { }
});
</code></pre>
<p>I have tried various <code>ui.id</code> etc. which doesn't seem to work.</p>
|
[
{
"answer_id": 197505,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 6,
"selected": true,
"text": "<p>Is it not the ui.draggable?</p>\n\n<p>If you go here (in Firefox and assuming you have firebug) and look in the firebug console youll see I am doing a console.dir of the ui.draggable object which is the div being dragged</p>\n\n<p><a href=\"http://jsbin.com/ixizi\" rel=\"noreferrer\">http://jsbin.com/ixizi</a></p>\n\n<p>Therefore the code you need in the drop function is</p>\n\n<pre><code> drop: function(ev, ui) {\n //to get the id\n //ui.draggable.attr('id') or ui.draggable.get(0).id or ui.draggable[0].id\n console.dir(ui.draggable) \n }\n</code></pre>\n"
},
{
"answer_id": 197541,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>redquare is right, inside your function refer to <code>ui.draggable</code>:</p>\n\n<pre><code>$(\".drop\").droppable({ accept: \".block\", \n activeClass: 'droppable-active', \n hoverClass: 'droppable-hover', \n drop: function(ev, ui) { \n //do something with ui.draggable here\n }\n});\n</code></pre>\n\n<p>That property points to the thing being dragged.</p>\n\n<p>Note that if you're using cloned \"helpers\", the draggable will be the cloned copy, not the original.</p>\n"
},
{
"answer_id": 660456,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$(ui.draggable).attr(\"id\") \n</code></pre>\n\n<p>...</p>\n"
},
{
"answer_id": 5634297,
"author": "karvonen",
"author_id": 255906,
"author_profile": "https://Stackoverflow.com/users/255906",
"pm_score": 4,
"selected": false,
"text": "<p>The ui.draggable() does not seem to work any more. To get the id one can use</p>\n\n<pre><code>$(event.target).attr(\"id\");\n</code></pre>\n"
},
{
"answer_id": 6407336,
"author": "Desperado",
"author_id": 290423,
"author_profile": "https://Stackoverflow.com/users/290423",
"pm_score": 2,
"selected": false,
"text": "<p>i got </p>\n\n<pre><code>drop: function( event, ui ) {alert(ui.draggable.attr(\"productid\"));}\n</code></pre>\n"
},
{
"answer_id": 9196232,
"author": "Daniel Mlodecki",
"author_id": 1011325,
"author_profile": "https://Stackoverflow.com/users/1011325",
"pm_score": 3,
"selected": false,
"text": "<p>I tried most of the above, but in the end only</p>\n\n<pre><code>event.target.id\n</code></pre>\n\n<p>worked for me.</p>\n"
},
{
"answer_id": 28863093,
"author": "Maurits Moeys",
"author_id": 4441216,
"author_profile": "https://Stackoverflow.com/users/4441216",
"pm_score": 3,
"selected": false,
"text": "<p><strong>ANSWER THAT WORKS IN 2017</strong></p>\n\n<p>A lot of time has passed by, and I found that the current accepted answer no longer works.</p>\n\n<p>A solution that currently works:</p>\n\n<pre><code>$('#someDraggableGroup').draggable({\n helper: 'clone',\n start: function( event, ui ) {\n console.log(ui.helper.context)\n console.log(ui.helper.clone())\n }\n })\n</code></pre>\n\n<p>Here, <code>ui.helper.context</code> refers to the original object you're trying to drag, and <code>clone()</code> refers to the cloned version. </p>\n\n<p>EDIT</p>\n\n<p>The above is too see which object you're dragging using the <code>draggable()</code> function. For detecting what <code>draggable</code> object was dropped in a <code>droppable()</code>, the following works:</p>\n\n<pre><code>$('#myDroppable').droppable({\n drop: function(event, ui){\n console.log(ui.draggable.context)\n OR\n console.log(ui.draggable.clone() )\n }\n})\n</code></pre>\n"
},
{
"answer_id": 51871202,
"author": "Shailesh Dwivedi",
"author_id": 7051725,
"author_profile": "https://Stackoverflow.com/users/7051725",
"pm_score": 0,
"selected": false,
"text": "<p><strong>How to manipulate clone object in any jquery ui operation ?</strong></p>\n\n<p>Just target ui outer html and use normal html jquery selectors</p>\n\n<pre><code>var target_ui_object_html=$(ui.item.context).attr(\"your attributes\");\n</code></pre>\n\n<blockquote>\n <p>attributes => id ,class ,rel,alt ,title or custom attr like data-name\n , data-user</p>\n</blockquote>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
I am using the jQuery library to implement drag and drop.
How do I get at the element that is being dragged when it is dropped?
I want to get the id of the image inside the div. The following element is dragged:
```
<div class="block">
<asp:Image ID="Image9" AlternateText="10/12/2008 - Retina" Width=81 Height=84 ImageUrl="~/uploads/ImageModifier/retina.jpg" runat=server />
</div>
```
I have the standard dropped function from their example:
```
$(".drop").droppable({
accept: ".block",
activeClass: 'droppable-active',
hoverClass: 'droppable-hover',
drop: function(ev, ui) { }
});
```
I have tried various `ui.id` etc. which doesn't seem to work.
|
Is it not the ui.draggable?
If you go here (in Firefox and assuming you have firebug) and look in the firebug console youll see I am doing a console.dir of the ui.draggable object which is the div being dragged
<http://jsbin.com/ixizi>
Therefore the code you need in the drop function is
```
drop: function(ev, ui) {
//to get the id
//ui.draggable.attr('id') or ui.draggable.get(0).id or ui.draggable[0].id
console.dir(ui.draggable)
}
```
|
197,497 |
<p>What is the best way to determine how many window handles an application is using? Is there a tool or a WMI performance counter that I could use?</p>
<p>I would like to run up an app and watch a counter of some sort and see that the number of window handles is increasing. </p>
<pre><code>for (int i=0; i < 1000; i++)
{
System.Threading.Thread.Sleep(1000);
RichTextBox rt = new RichTextBox();
rt.Text = "hi";
this.Controls.Add(rt);
}
</code></pre>
<p>I am running the above code and watching the "Handle Count" counter on the process, and it does not seem to be increasing. Is there something I am looking at incorrectly?</p>
|
[
{
"answer_id": 197504,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 5,
"selected": true,
"text": "<p>Perfmon, which comes with your computer can do it. You can also add a column to your task manager processes tab (Handle Count).</p>\n\n<p>Instructions for Perfmon</p>\n\n<ol>\n<li>Add a counter (click the +)</li>\n<li>Choose Process under Performance object</li>\n<li>Choose Handle Count under the counter list</li>\n<li>Choose your process from the instance list</li>\n<li>Click Add, click Close</li>\n</ol>\n\n<p>To get the graph in range, you have to right-click it in the list, choose properties, and then choose the right scale (.1 or .01 would probably be right)</p>\n\n<p>Edit (in response to added information): I think you just proved that creating RichTextBoxes doesn't result in Handles being allocated. I don't think it really needs one until you are editing the control and it might be smart enough to do that, since allocating too many resources for a control that isn't active would make it hard to have a lot of controls on a form (think about Excel, for example).</p>\n"
},
{
"answer_id": 197581,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Process Monitor</a> is very handy in interactively monitoring all sorts of resources used by Windows processes.</p>\n\n<blockquote>\n <p>Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity.</p>\n</blockquote>\n\n<p>Note - if you mean finding the information programatically, <em>.Net</em> provides access to all performance counters. You use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter(VS.71).aspx\" rel=\"nofollow noreferrer\"> System.Diagnostics.PerformanceCounter</a> Class like this:</p>\n\n<pre><code>PerformanceCounter PC=new PerformanceCounter();\nPC.CategoryName=\"Process\";\nPC.CounterName=\"Handles\";\nPC.InstanceName=\"MyProc\";\nMessageBox.Show(PC.NextValue().ToString());\n</code></pre>\n"
},
{
"answer_id": 198394,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 0,
"selected": false,
"text": "<p>The handle count shown by taskmanager is the same as the one shown by PerfMon</p>\n\n<p>ProcessExplorer tool from sysinternals can list the different type of handles + their names a process uses and you can get a good idea by browsing that list about the composition of the handles your program uses. </p>\n\n<p>But I'm afraid it does not sumarize these handle type counts for you. </p>\n\n<p>To view the actual handles and their types using ProcessExplorer - View - show lower pane view - handles.</p>\n\n<p>You can also use some sort window spy tool which shows all the windows in the system like Microsoft spy++ or Managed Spy++ (<a href=\"http://msdn.microsoft.com/en-us/magazine/cc163617.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163617.aspx</a>)</p>\n\n<p>This will allow you to see if your windows are being created.</p>\n"
},
{
"answer_id": 1496777,
"author": "user24770",
"author_id": 24770,
"author_profile": "https://Stackoverflow.com/users/24770",
"pm_score": 0,
"selected": false,
"text": "<p>Perfmon or Task Manager cannot give you the number of WINDOW handles used by a process only the total number of handles of all types (file, thread, etc.). </p>\n\n<p>The best information that I can find on the subject is <a href=\"http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/1d4e53a7-5697-49b4-913b-d1d4606eb372\" rel=\"nofollow noreferrer\">this</a> post which indicates that the window handle count for a process can be determined by enumerating all child windows of the main process window.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/324/"
] |
What is the best way to determine how many window handles an application is using? Is there a tool or a WMI performance counter that I could use?
I would like to run up an app and watch a counter of some sort and see that the number of window handles is increasing.
```
for (int i=0; i < 1000; i++)
{
System.Threading.Thread.Sleep(1000);
RichTextBox rt = new RichTextBox();
rt.Text = "hi";
this.Controls.Add(rt);
}
```
I am running the above code and watching the "Handle Count" counter on the process, and it does not seem to be increasing. Is there something I am looking at incorrectly?
|
Perfmon, which comes with your computer can do it. You can also add a column to your task manager processes tab (Handle Count).
Instructions for Perfmon
1. Add a counter (click the +)
2. Choose Process under Performance object
3. Choose Handle Count under the counter list
4. Choose your process from the instance list
5. Click Add, click Close
To get the graph in range, you have to right-click it in the list, choose properties, and then choose the right scale (.1 or .01 would probably be right)
Edit (in response to added information): I think you just proved that creating RichTextBoxes doesn't result in Handles being allocated. I don't think it really needs one until you are editing the control and it might be smart enough to do that, since allocating too many resources for a control that isn't active would make it hard to have a lot of controls on a form (think about Excel, for example).
|
197,508 |
<p>I know mime_content_type() is deprecated, but it seemed to me the alternative is worse at the moment. <code>Finfo</code> seems to require adding files and changing ini directions on windows; I don't want to require this for the script I am making.</p>
<p>I need to find the mimetype of files, but when calling <code>mime_content_type($filename)</code> on windows it fails. mime_magic.magicfile points to the correct file, but when enabling mime_magic.debug in the ini file, I get this error message:</p>
<p><code><b>Warning:</b> mime_content_type()[<a href="http://www.php.net/mime_magic]" rel="nofollow noreferrer">http://www.php.net/mime_magic]</a>: mime_magic not initialized in <b>C:\xampp\htdocs\test.php</b> on line <b>2</b></code></p>
<p>I am not sure if that is a problem or if it still happens when I disable the debugging and it just doesn't tell me. </p>
<p>I checked, and <code>extension=php_mime_magic.dll</code> is enabled in the ini file and httpd.conf specifies <pre><code>LoadModule mime_module modules/mod_mime.so
#LoadModule mime_magic_module modules/mod_mime_magic.so</code></pre></p>
<p>I am using XAMPP 1.6.5.</p>
|
[
{
"answer_id": 197538,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 1,
"selected": false,
"text": "<p>This may be related to <a href=\"http://bugs.php.net/bug.php?id=38235\" rel=\"nofollow noreferrer\">this bug report</a>. Do you have any errors in your error log when you call the script along the lines of <code>'FOO' is not a valid mimetype, entry skipped</code>?</p>\n<p>Unfortunately the final response in that particular thread was to go ahead and use <code><a href=\"http://pecl.php.net/package/Fileinfo\" rel=\"nofollow noreferrer\">Fileinfo</a></code>..</p>\n<p>Reading through <a href=\"http://www.daniweb.com/forums/post537410.html\" rel=\"nofollow noreferrer\">another thread</a> describing the same problem - when you turned on debug, did you set it to "On" or 1? Shouldn't make a difference, but in the thread linked above that seems like part of the solution in that case.</p>\n<hr>\n<blockquote>\n<p>I am not sure if that is a problem or if it still happens when I disable the debugging and it just doesn't tell me.</p>\n</blockquote>\n<p>What are you getting when you echo out the value of <code>mime_content_type</code> with debugging turned off?</p>\n"
},
{
"answer_id": 199108,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Finfo seems to require adding files and changing ini directions on windows; I don't want to require this for the script I am making.</p>\n</blockquote>\n\n<p>Have you tried <a href=\"http://docs.php.net/manual/en/function.finfo-buffer.php\" rel=\"nofollow noreferrer\"><code>finfo_buffer</code></a>? That allows you to use the file as a string, so you could do:</p>\n\n<pre><code>$finfo = new finfo;\n$filename = $_GET['filename'];\nvar_dump($finfo->buffer(file_get_contents($filename)));\n</code></pre>\n\n<p>Also an issue from that bug report was that the mime database was out of date - have you tried with a different copy?</p>\n"
},
{
"answer_id": 1710806,
"author": "Jonathon Hill",
"author_id": 168815,
"author_profile": "https://Stackoverflow.com/users/168815",
"pm_score": 0,
"selected": false,
"text": "<p>Fileinfo can be a trick to get going on Windows. Instructions here: <a href=\"http://forums.zend.com/viewtopic.php?f=8&t=337#p14681\" rel=\"nofollow noreferrer\">http://forums.zend.com/viewtopic.php?f=8&t=337#p14681</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6752/"
] |
I know mime\_content\_type() is deprecated, but it seemed to me the alternative is worse at the moment. `Finfo` seems to require adding files and changing ini directions on windows; I don't want to require this for the script I am making.
I need to find the mimetype of files, but when calling `mime_content_type($filename)` on windows it fails. mime\_magic.magicfile points to the correct file, but when enabling mime\_magic.debug in the ini file, I get this error message:
`**Warning:** mime_content_type()[<http://www.php.net/mime_magic]>: mime_magic not initialized in **C:\xampp\htdocs\test.php** on line **2**`
I am not sure if that is a problem or if it still happens when I disable the debugging and it just doesn't tell me.
I checked, and `extension=php_mime_magic.dll` is enabled in the ini file and httpd.conf specifies
```
LoadModule mime_module modules/mod_mime.so
#LoadModule mime_magic_module modules/mod_mime_magic.so
```
I am using XAMPP 1.6.5.
|
This may be related to [this bug report](http://bugs.php.net/bug.php?id=38235). Do you have any errors in your error log when you call the script along the lines of `'FOO' is not a valid mimetype, entry skipped`?
Unfortunately the final response in that particular thread was to go ahead and use `[Fileinfo](http://pecl.php.net/package/Fileinfo)`..
Reading through [another thread](http://www.daniweb.com/forums/post537410.html) describing the same problem - when you turned on debug, did you set it to "On" or 1? Shouldn't make a difference, but in the thread linked above that seems like part of the solution in that case.
---
>
> I am not sure if that is a problem or if it still happens when I disable the debugging and it just doesn't tell me.
>
>
>
What are you getting when you echo out the value of `mime_content_type` with debugging turned off?
|
197,521 |
<p>I must implement a web service which expose a list of values (integers, custom classes etc).
My working solution returns a <code>List<T></code>, and according to FxCop it is better to return a <code>Collection<T></code> or <code>ReadOnlyCollection<T></code>.</p>
<p>If I choose to return a <code>ReadOnlyCollection<T></code>, the web service shows an error like:</p>
<blockquote>
<p>To be XML serializable, types which inherit from <code>ICollection</code> must have an implementation of <code>Add(System.Int32)</code> at all levels of their inheritance hierarchy.
<code>System.Collections.ObjectModel.ReadOnlyCollection</code> <code>1</code> <code>[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</code> does not implement <code>Add(System.Int32)</code>.</p>
</blockquote>
<p>What is your favorite way to use internally a <code>List<T></code> and expose a <code>Collection<T></code> ? (using C#, and preferably framework 2.0 only)</p>
|
[
{
"answer_id": 197530,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<p>List<T> or Collection<T> are fine in this case.</p>\n\n<p>In terms of the original question, you can wrap a List<T> in a Collection<T> very simply:</p>\n\n<pre><code>List<Foo> list = new List<Foo>();\n// ...\nCollection<Foo> col = new Collection<Foo>(list);\n</code></pre>\n\n<p>This is a true wrapper; add an item to the wrapper (col), and it gets added to the list. This can be slightly confusing, because many such constructors use the argument to do the initial population, but don't link to the original list. Collection<T> is an exception ;-p</p>\n\n<p>Since you are on a web-service boundary, that recommendation from FxCop doesn't apply. That is useful (inline with <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx\" rel=\"noreferrer\">Eric Lippert's recent blog</a>) to prevent a caller stomping over the callee's memory - but in a web-service distributed scenario that simply doesn't apply. In fact, since web-services have a few well documented issues with certain generic scenarios, a simple array is arguably very usable and pragmatic at a web-service boundary. In the context of Eric's blog - in this case, there is no question of the caller/callee issue, since there is an enforced barrier between the two. </p>\n\n<p>In terms of WSDL/mex, I suspect all 3 (list/collection/array) will just become a block of elements - so you may a well go with whichever is most convenient.</p>\n"
},
{
"answer_id": 197679,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 1,
"selected": false,
"text": "<p>I usually return IList<T> from a WCF web service: FxCop is happy enough with this.\nNot sure if this works with ASMX web services.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19756/"
] |
I must implement a web service which expose a list of values (integers, custom classes etc).
My working solution returns a `List<T>`, and according to FxCop it is better to return a `Collection<T>` or `ReadOnlyCollection<T>`.
If I choose to return a `ReadOnlyCollection<T>`, the web service shows an error like:
>
> To be XML serializable, types which inherit from `ICollection` must have an implementation of `Add(System.Int32)` at all levels of their inheritance hierarchy.
> `System.Collections.ObjectModel.ReadOnlyCollection` `1` `[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]` does not implement `Add(System.Int32)`.
>
>
>
What is your favorite way to use internally a `List<T>` and expose a `Collection<T>` ? (using C#, and preferably framework 2.0 only)
|
List<T> or Collection<T> are fine in this case.
In terms of the original question, you can wrap a List<T> in a Collection<T> very simply:
```
List<Foo> list = new List<Foo>();
// ...
Collection<Foo> col = new Collection<Foo>(list);
```
This is a true wrapper; add an item to the wrapper (col), and it gets added to the list. This can be slightly confusing, because many such constructors use the argument to do the initial population, but don't link to the original list. Collection<T> is an exception ;-p
Since you are on a web-service boundary, that recommendation from FxCop doesn't apply. That is useful (inline with [Eric Lippert's recent blog](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx)) to prevent a caller stomping over the callee's memory - but in a web-service distributed scenario that simply doesn't apply. In fact, since web-services have a few well documented issues with certain generic scenarios, a simple array is arguably very usable and pragmatic at a web-service boundary. In the context of Eric's blog - in this case, there is no question of the caller/callee issue, since there is an enforced barrier between the two.
In terms of WSDL/mex, I suspect all 3 (list/collection/array) will just become a block of elements - so you may a well go with whichever is most convenient.
|
197,606 |
<p>I'm exploring various options for mapping common C# code constructs to C++ CUDA code for running on a GPU. The structure of the system is as follows (arrows represent method calls):</p>
<p>C# program -> C# GPU lib -> C++ CUDA implementation lib</p>
<p>A method in the GPU library could look something like this:</p>
<pre><code>public static void Map<T>(this ICollection<T> c, Func<T,T> f)
{
//Call 'f' on each element of 'c'
}
</code></pre>
<p>This is an extension method to ICollection<> types which runs a function on each element. However, what I would like it to do is to call the C++ library and make it run the methods on the GPU. This would require the function to be, somehow, translated into C++ code. Is this possible?</p>
<p>To elaborate, if the user of my library executes a method (in C#) with some arbitrary code in it, I would like to translate this code into the C++ equivelant such that I can run it on CUDA. I have the feeling that there are no easy way to do this but I would like to know if there are any way to do it or to achieve some of the same effect.</p>
<p>One thing I was wondering about is capturing the function to translate in an Expression and use this to map it to a C++ equivelant. Anyone has any experience with this?</p>
|
[
{
"answer_id": 197630,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "<p>There's <a href=\"http://www.gass-ltd.co.il/en/products/cuda.net/\" rel=\"nofollow noreferrer\">CUDA.Net</a> if you want some reference how C# can be run on GPU.</p>\n"
},
{
"answer_id": 197650,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 2,
"selected": false,
"text": "<p>To be honest, I'm not sure I fully understand what you are getting at. However, you may be interested in this project which converts .Net applications / libraries into straight C++ w/o any .Net framework required. <a href=\"http://www.codeplex.com/crossnet\" rel=\"nofollow noreferrer\">http://www.codeplex.com/crossnet</a></p>\n"
},
{
"answer_id": 319142,
"author": "Die in Sente",
"author_id": 40756,
"author_profile": "https://Stackoverflow.com/users/40756",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting question. I'm not very expert at C#, but I think an ICollection is a container of <em>objects</em>. If each element of c was, say, a pixel, you'd have to do a lot of marshalling to convert that into a buffer of bytes or floats that CUDA could use. I suspect that would slow everything down enough to negate the advantage of doing anything on the gpu.</p>\n"
},
{
"answer_id": 319174,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>What you could do would be to write an own <a href=\"http://msdn.microsoft.com/en-us/library/bb546158.aspx\" rel=\"nofollow noreferrer\"><code>IQueryable</code> LINQ provider</a>, as is done for <a href=\"http://msdn.microsoft.com/en-us/library/bb425822.aspx\" rel=\"nofollow noreferrer\">LINQ to SQL</a> to translate LINQ queries to SQL.</p>\n\n<p>However, one problem that I see with this approach is the fact that LINQ queries are usually evaluated lazily. In order to benefit from pipelining, this is probably not a viable solution.</p>\n\n<p>It might also be worth investigating how to implement Google’s <a href=\"http://labs.google.com/papers/mapreduce.html\" rel=\"nofollow noreferrer\">MapReduce API</a> for C# and CUDA and then use an approach similar to <a href=\"http://mathema.tician.de/software/pycuda\" rel=\"nofollow noreferrer\">PyCuda</a> to ship the logic to the GPU. In that context, it might also be useful to take a look at the already existing <a href=\"http://www.nvidia.com/object/cuda_home.html#state=detailsOpen;aid=f6a4e7d4-7f25-41f8-aa92-83305b61867d\" rel=\"nofollow noreferrer\">MapReduce implementation in CUDA</a>.</p>\n"
},
{
"answer_id": 1103998,
"author": "cr333",
"author_id": 72470,
"author_profile": "https://Stackoverflow.com/users/72470",
"pm_score": 0,
"selected": false,
"text": "<p>That's a very interesting question and I have no idea how to do this.</p>\n\n<p>However, the <a href=\"http://brahma.ananthonline.net/\" rel=\"nofollow noreferrer\">Brahma library</a> seems to do something very similar. You can define functions using LINQ which are then compiled to GLSL shaders to run efficiently on a GPU. Have a look at their <a href=\"http://sourceforge.net/projects/brahma-fx/\" rel=\"nofollow noreferrer\">code</a> and in particular the <a href=\"http://brahma-fx.svn.sourceforge.net/viewvc/brahma-fx/trunk/Source/Samples/OpenGL/GameOfLife/Form1.cs?view=markup\" rel=\"nofollow noreferrer\">Game of Life</a> sample.</p>\n"
},
{
"answer_id": 1109201,
"author": "Eric",
"author_id": 74601,
"author_profile": "https://Stackoverflow.com/users/74601",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend the following process to accelerate some of your computation using CUDA from a C# program:</p>\n\n<ul>\n<li>First, create an <strong><em>unmanaged</em></strong> C++ library that you P/Invoke for the functions you want to accelerate. This will restrict you more or less to the data types you can easily work with in CUDA.</li>\n<li>Integrate your unmanaged library with your C# application. If you're doing things correctly, you should already notice some kind of speed up. If not, you should probably give up.</li>\n<li>Replace the C++ functions inside your library (without changing its interface) to perform the computations on the GPU with CUDA kernels.</li>\n</ul>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
I'm exploring various options for mapping common C# code constructs to C++ CUDA code for running on a GPU. The structure of the system is as follows (arrows represent method calls):
C# program -> C# GPU lib -> C++ CUDA implementation lib
A method in the GPU library could look something like this:
```
public static void Map<T>(this ICollection<T> c, Func<T,T> f)
{
//Call 'f' on each element of 'c'
}
```
This is an extension method to ICollection<> types which runs a function on each element. However, what I would like it to do is to call the C++ library and make it run the methods on the GPU. This would require the function to be, somehow, translated into C++ code. Is this possible?
To elaborate, if the user of my library executes a method (in C#) with some arbitrary code in it, I would like to translate this code into the C++ equivelant such that I can run it on CUDA. I have the feeling that there are no easy way to do this but I would like to know if there are any way to do it or to achieve some of the same effect.
One thing I was wondering about is capturing the function to translate in an Expression and use this to map it to a C++ equivelant. Anyone has any experience with this?
|
There's [CUDA.Net](http://www.gass-ltd.co.il/en/products/cuda.net/) if you want some reference how C# can be run on GPU.
|
197,614 |
<p>In chapter 2, the section on bitwise operators (section 2.9), I'm having trouble understanding how one of the sample methods works.</p>
<p>Here's the method provided:</p>
<pre><code>unsigned int getbits(unsigned int x, int p, int n) {
return (x >> (p + 1 - n)) & ~(~0 << n);
}
</code></pre>
<p>The idea is that, for the given number <em>x</em>, it will return the <em>n</em> bits starting at position <em>p</em>, counting from the right (with the farthest right bit being position 0). Given the following <code>main()</code> method:</p>
<pre><code>int main(void) {
int x = 0xF994, p = 4, n = 3;
int z = getbits(x, p, n);
printf("getbits(%u (%x), %d, %d) = %u (%X)\n", x, x, p, n, z, z);
return 0;
}
</code></pre>
<p>The output is:</p>
<blockquote>
<p><code>getbits(63892 (f994), 4, 3) = 5 (5)</code></p>
</blockquote>
<p>I get portions of this, but am having trouble with the "big picture," mostly because of the bits (no pun intended) that I don't understand.</p>
<p>The part I'm specifically having issues with is the complements piece: <code>~(~0 << n)</code>. I think I get the first part, dealing with <em>x</em>; it's this part (and then the mask) that I'm struggling with -- and how it all comes together to actually retrieve those bits. (Which I've verified it is doing, both with code and checking my results using calc.exe -- thank God it has a binary view!)</p>
<p>Any help?</p>
|
[
{
"answer_id": 197652,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 6,
"selected": true,
"text": "<p>Let's use 16 bits for our example. In that case, <code>~0</code> is equal to</p>\n<pre><code>1111111111111111\n</code></pre>\n<p>When we left-shift this <code>n</code> bits (3 in your case), we get:</p>\n<pre><code>1111111111111000\n</code></pre>\n<p>because the <code>1</code>s at the left are discarded and <code>0</code>s are fed in at the right. Then re-complementing it gives:</p>\n<pre><code>0000000000000111\n</code></pre>\n<p>so it's just a clever way to get <code>n</code> 1-bits in the least significant part of the number.</p>\n<p>The "x bit" you describe has shifted the given number (<code>f994 = 1111 1001 1001 0100</code>) right far enough so that the least significant 3 bits are the ones you want. In this example, the input bits you're requesting are there, all other input bits are marked <code>.</code> since they're not important to the final result:</p>\n<pre><code>ff94 ...........101.. # original number\n>> p+1-n [2] .............101 # shift desired bits to right\n& ~(~0 << n) [7] 0000000000000101 # clear all the other (left) bits\n</code></pre>\n<p>As you can see, you now have the relevant bits, in the rightmost bit positions.</p>\n"
},
{
"answer_id": 197655,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Using the example:\nint x = 0xF994, p = 4, n = 3;\n int z = getbits(x, p, n);</p>\n\n<p>and focusing on this set of operations\n ~(~0 << n)</p>\n\n<p>for any bit set (10010011 etc) you want to generate a \"mask\" that pulls only the bits you want to see. So 10010011 or 0x03, I'm interested in xxxxx011. What is the mask that will extract that set ? 00000111 Now I want to be sizeof int independent, I'll let the machine do the work i.e. start with 0 for a byte machine it's 0x00 for a word machine it's 0x0000 etc. 64 bit machine would represent by 64 bits or 0x0000000000000000\n<br><br>\nNow apply \"not\" (~0) and get 11111111<br>\nshift right (<<) by n and get 11111000<br>\nand \"not\" that and get 00000111<br>\n<br>\nso 10010011 & 00000111 = 00000011\n<br> You remember how boolean operations work ?</p>\n"
},
{
"answer_id": 197660,
"author": "David Grant",
"author_id": 26829,
"author_profile": "https://Stackoverflow.com/users/26829",
"pm_score": 3,
"selected": false,
"text": "<p><code>~(~0 << n)</code> creates a mask that will have the <code>n</code> right-most bits turned on.</p>\n\n<pre><code>0\n 0000000000000000\n~0\n 1111111111111111\n~0 << 4\n 1111111111110000\n~(~0 << 4)\n 0000000000001111\n</code></pre>\n\n<p>ANDing the result with something else will return what's in those <code>n</code> bits.</p>\n\n<p>Edit: I wanted to point out this programmer's calculator I've been using forever: <a href=\"http://www.analogx.com/contents/download/Programming/pcalc/Freeware.htm\" rel=\"nofollow noreferrer\">AnalogX PCalc</a>.</p>\n"
},
{
"answer_id": 197866,
"author": "None",
"author_id": 25012,
"author_profile": "https://Stackoverflow.com/users/25012",
"pm_score": 4,
"selected": false,
"text": "<p>I would say the best thing to do is to do a problem out by hand, that way you'll understand how it works. </p>\n\n<p>Here is what I did using an 8-bit unsigned int.</p>\n\n<ol>\n<li><p>Our number is 75 we want the 4 bits starting from position 6.\nthe call for the function would be getbits(75,6,4);</p></li>\n<li><p>75 in binary is 0100 1011</p></li>\n<li><p>So we create a mask that is 4 bits long starting with the lowest order bit this is done as such.</p></li>\n</ol>\n\n<p>~0 = 1111 1111<br>\n<<4 = 1111 0000<br>\n~ = 0000 1111</p>\n\n<p>Okay we got our mask.</p>\n\n<ol start=\"4\">\n<li>Now, we push the bits we want out of the number into the lowest order bits so\nwe shift binary 75 by 6+1-4=3.</li>\n</ol>\n\n<p>0100 1011 >>3 0000 1001</p>\n\n<p>Now we have a mask of the correct number of bits in the low order and the bits we want out of the original number in the low order.</p>\n\n<ol start=\"4\">\n<li>so we & them<br></li>\n</ol>\n\n<pre>\n 0000 1001 <br />\n& 0000 1111\n============\n\n 0000 1001\n\n</pre>\n\n<p>so the answer is decimal 9. </p>\n\n<p><b>Note:</b> the higher order nibble just happens to be all zeros, making the masking redundant in this case but it could have been anything depending on the value of the number we started with.</p>\n"
},
{
"answer_id": 37164128,
"author": "M.M",
"author_id": 1505939,
"author_profile": "https://Stackoverflow.com/users/1505939",
"pm_score": 2,
"selected": false,
"text": "<p>Nobody mentioned it yet, but in ANSI C <code>~0 << n</code> causes undefined behaviour.</p>\n\n<p>This is because <code>~0</code> is a negative number and left-shifting negative numbers is undefined.</p>\n\n<p>Reference: C11 6.5.7/4 (earlier versions had similar text)</p>\n\n<blockquote>\n <p>The result of <code>E1 << E2</code> is <code>E1</code> left-shifted <code>E2</code> bit positions; vacated bits are filled with zeros. [...] If E1 has a signed\n type and nonnegative value, and <code>E1</code> × <code>2</code><SUP><code>E2</code></SUP> is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.</p>\n</blockquote>\n\n<p>In K&R C this code would have relied on the particular class of system that K&R developed on, naively shifting <code>1</code> bits off the left when performing left-shift of a signed number (and this code also relies on 2's complement representation), but some other systems don't share those properties so the C standardization process did not define this behaviour.</p>\n\n<p>So this example is really only interesting as a historical curiosity, it should not be used in any real code since 1989 (if not earlier).</p>\n"
},
{
"answer_id": 48939440,
"author": "Surfer Boy",
"author_id": 9399238,
"author_profile": "https://Stackoverflow.com/users/9399238",
"pm_score": -1,
"selected": false,
"text": "<p>In <code>ANSI C ~0 >> n</code> causes undefined behavior </p>\n\n<p>// the post about left shifting causing a problem is wrong.</p>\n\n<p>unsigned char m,l;</p>\n\n<p>m = ~0 >> 4; is producing 255 and its equal to ~0 but, </p>\n\n<p>m = ~0;\nl = m >> 4; is producing correct value 15 same as:</p>\n\n<p>m = 255 >> 4;</p>\n\n<p>there is no problem with left shifting negative <code>~0 <<</code> whatsoever </p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14048/"
] |
In chapter 2, the section on bitwise operators (section 2.9), I'm having trouble understanding how one of the sample methods works.
Here's the method provided:
```
unsigned int getbits(unsigned int x, int p, int n) {
return (x >> (p + 1 - n)) & ~(~0 << n);
}
```
The idea is that, for the given number *x*, it will return the *n* bits starting at position *p*, counting from the right (with the farthest right bit being position 0). Given the following `main()` method:
```
int main(void) {
int x = 0xF994, p = 4, n = 3;
int z = getbits(x, p, n);
printf("getbits(%u (%x), %d, %d) = %u (%X)\n", x, x, p, n, z, z);
return 0;
}
```
The output is:
>
> `getbits(63892 (f994), 4, 3) = 5 (5)`
>
>
>
I get portions of this, but am having trouble with the "big picture," mostly because of the bits (no pun intended) that I don't understand.
The part I'm specifically having issues with is the complements piece: `~(~0 << n)`. I think I get the first part, dealing with *x*; it's this part (and then the mask) that I'm struggling with -- and how it all comes together to actually retrieve those bits. (Which I've verified it is doing, both with code and checking my results using calc.exe -- thank God it has a binary view!)
Any help?
|
Let's use 16 bits for our example. In that case, `~0` is equal to
```
1111111111111111
```
When we left-shift this `n` bits (3 in your case), we get:
```
1111111111111000
```
because the `1`s at the left are discarded and `0`s are fed in at the right. Then re-complementing it gives:
```
0000000000000111
```
so it's just a clever way to get `n` 1-bits in the least significant part of the number.
The "x bit" you describe has shifted the given number (`f994 = 1111 1001 1001 0100`) right far enough so that the least significant 3 bits are the ones you want. In this example, the input bits you're requesting are there, all other input bits are marked `.` since they're not important to the final result:
```
ff94 ...........101.. # original number
>> p+1-n [2] .............101 # shift desired bits to right
& ~(~0 << n) [7] 0000000000000101 # clear all the other (left) bits
```
As you can see, you now have the relevant bits, in the rightmost bit positions.
|
197,624 |
<p>Is it possible to integrate my PHP web-based ecommerce application with Quickbook Online Edition?</p>
<p>When I make a sale on my web site, I would like to be able to make the corresponding journal entry in my accounting books.</p>
<p>Note, I'm referring to Quickbook <strong>Online Edition</strong>, <strong>not</strong> the desktop software.</p>
|
[
{
"answer_id": 197836,
"author": "inxilpro",
"author_id": 12549,
"author_profile": "https://Stackoverflow.com/users/12549",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like Quickbooks OE has an XML-based SDK, available at:</p>\n\n<p><a href=\"http://developer.intuit.com/technical_resources/default.aspx?id=1492\" rel=\"nofollow noreferrer\">http://developer.intuit.com/technical_resources/default.aspx?id=1492</a></p>\n"
},
{
"answer_id": 273953,
"author": "Keith Palmer Jr.",
"author_id": 26133,
"author_profile": "https://Stackoverflow.com/users/26133",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, you can send qbXML requests to QuickBooks Online Edition, just as you can send qbXML requests to regular desktop editions of QuickBooks. </p>\n\n<p>Download the QuickBooks SDK for more details. </p>\n"
},
{
"answer_id": 532455,
"author": "Keith Palmer Jr.",
"author_id": 26133,
"author_profile": "https://Stackoverflow.com/users/26133",
"pm_score": 4,
"selected": false,
"text": "<p>I now have built a set of PHP classes that facilitates communication with QuickBooks Online Edition. It makes communicating with QuickBooks Online Edition as easy as: </p>\n\n<pre><code>// Create the connection to QuickBooks\n$API = new QuickBooks_API(...);\n\n// Build the Customer object\n$Customer = new QuickBooks_Object_Customer();\n$Customer->setName($name);\n$Customer->setShipAddress('134 Stonemill Road', '', '', '', '', 'Storrs', 'CT', '', '06268');\n\n// Send the request to QuickBooks\n$API->addCustomer($Customer, '_add_customer_callback', 15);\n\n// The framework also supports processing raw qbXML requests\n$API->qbxml('\n <CustomerQueryRq>\n <FullName>Keith Palmer Jr.</FullName>\n </CustomerQueryRq>', '_raw_qbxml_callback');\n</code></pre>\n\n<p>You can download the framework from my thread here:\n<a href=\"https://idnforums.intuit.com/messageview.aspx?catid=56&threadid=9164\" rel=\"noreferrer\">QuickBooks Online Edition PHP Package</a></p>\n\n<p>I've started writing some documentation/tips on how to integrate web applications with QuickBooks Online Edition here: \n<a href=\"http://wiki.consolibyte.com/wiki/doku.php/quickbooks_online_edition\" rel=\"noreferrer\">QuickBooks Integration wiki</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is it possible to integrate my PHP web-based ecommerce application with Quickbook Online Edition?
When I make a sale on my web site, I would like to be able to make the corresponding journal entry in my accounting books.
Note, I'm referring to Quickbook **Online Edition**, **not** the desktop software.
|
I now have built a set of PHP classes that facilitates communication with QuickBooks Online Edition. It makes communicating with QuickBooks Online Edition as easy as:
```
// Create the connection to QuickBooks
$API = new QuickBooks_API(...);
// Build the Customer object
$Customer = new QuickBooks_Object_Customer();
$Customer->setName($name);
$Customer->setShipAddress('134 Stonemill Road', '', '', '', '', 'Storrs', 'CT', '', '06268');
// Send the request to QuickBooks
$API->addCustomer($Customer, '_add_customer_callback', 15);
// The framework also supports processing raw qbXML requests
$API->qbxml('
<CustomerQueryRq>
<FullName>Keith Palmer Jr.</FullName>
</CustomerQueryRq>', '_raw_qbxml_callback');
```
You can download the framework from my thread here:
[QuickBooks Online Edition PHP Package](https://idnforums.intuit.com/messageview.aspx?catid=56&threadid=9164)
I've started writing some documentation/tips on how to integrate web applications with QuickBooks Online Edition here:
[QuickBooks Integration wiki](http://wiki.consolibyte.com/wiki/doku.php/quickbooks_online_edition)
|
197,634 |
<p>With ASP.NET's view engine/template aspx/ashx pages the way to spit to screen seems to be: </p>
<pre><code><%= Person.Name %>
</code></pre>
<p>Which was fine with webforms as alot of model data was bound to controls programatically. But with MVC we are now using this syntax more oftern. </p>
<p>The issue I have with it is quite trivial, but annoying either way. This is that it seems to break up the mark up i.e.:</p>
<pre><code><% foreach(var Person in People) { %>
<%= Person.Name %>
<% } %>
</code></pre>
<p>That seems like alot of opening and closing tags to me!</p>
<p>Other view engines in the MVC contrib have a means of spitting to screen with out opening and closing the script tags using standard keyword such as "print, out, echo" i.e. (brail example):</p>
<pre><code><%
for element in list:
output "<li>${element}</li>"
end
%>
</code></pre>
<p>Now, I said this may seem trivial, but it just seems more readable this way. So what are the advantages of MS having this syntax, and not providing a output method?</p>
<p>Cheers, Chris.</p>
|
[
{
"answer_id": 197641,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 5,
"selected": true,
"text": "<p>Consider something like this, instead:</p>\n\n<pre><code><% foreach(var Person in People) { \n Response.Write(Person.Name); \n} %>\n</code></pre>\n\n<p>I believe that'll work. (Although I haven't tested it; I've only just begun with MVC and don't have the toolset here at the office.)</p>\n\n<p>EDIT: I apparently missed the actual question ... :)</p>\n\n<p>Microsoft does provide an output method, but didn't provide a syntax like the one you describe. The output method is <code>Response.Write()</code>. I can't answer this directly (I believe you'll need to check with Scott Hanselmann over at MS :)), but I think they didn't want to complicate scripting by adding yet-another-language for us to learn; I think they wanted to leverage the languages (C#, VB, etc.) which developers already knew.</p>\n\n<p>EDIT #2: I placed the following in a comment, and in retrospect (for completeness), it should be part of the answer.</p>\n\n<p>If you head over to the <a href=\"http://www.asp.net/learn/mvc/tutorial-04-cs.aspx\" rel=\"noreferrer\">Learn MVC site on ASP.NET</a>, in the view tutorial (that's the link), you'll see the following paragraph:</p>\n\n<blockquote>\n <p>Since you call <code>Response.Write()</code> so\n often, Microsoft provides you with a\n shortcut for calling the\n <code>Response.Write()</code> method. The view in\n Listing 3 uses the delimiters <code><%=</code> and\n <code>%></code> as a shortcut for calling\n <code>Response.Write()</code>.</p>\n</blockquote>\n\n<p>Essentially, <code><%= %></code> is the accepted shortcut for <code>Response.Write</code>, and you therefore can use the full <code>Response.Write</code> method anywhere you'd use <code><%= %></code>.</p>\n"
},
{
"answer_id": 197658,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 0,
"selected": false,
"text": "<p>What you're looking for is probably a different View engine -- they each handle embedded code like that in their own way. Check out <a href=\"http://andrewpeters.net/2007/12/19/introducing-nhaml-an-aspnet-mvc-view-engine/\" rel=\"nofollow noreferrer\">NHaml</a>, an ASP.Net port of Rails' <a href=\"http://haml.hamptoncatlin.com/\" rel=\"nofollow noreferrer\">Haml</a> engine.</p>\n\n<p>Some more view engines to look at: <a href=\"http://www.codeplex.com/MVCContrib/Wiki/View.aspx?title=Brail&referringTitle=Documentation\" rel=\"nofollow noreferrer\">Brail</a>,\n<a href=\"http://nvelocity.sourceforge.net/index.html\" rel=\"nofollow noreferrer\">NVelocity</a></p>\n"
},
{
"answer_id": 197665,
"author": "Owen",
"author_id": 425,
"author_profile": "https://Stackoverflow.com/users/425",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks guys,I dont specifically want to switch view engines, though I will take time to look at the other avaliable. I am sure you can understand that most MS development houses dont touch anything but MS branded technology so I just wanted to know if there was a way to do this with the default view engine. Or if not, why not? Is there a reason, if not where could I suggest the default view compiler add such a keywork. </p>\n\n<p>John- I believe that Response.Write(Person.Name) will just render the string to the top of the page, before any other output. Not 100% on that though, ill give it a bash. </p>\n\n<p>Edit:</p>\n\n<p>Apparently, Response.Write(Person.Name) works as suggested. Well that was easy. Thanks :-) John.</p>\n"
},
{
"answer_id": 197711,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>I've heard they're working on improving this for ASP.Net 4 via client templates.</p>\n"
},
{
"answer_id": 197750,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 0,
"selected": false,
"text": "<p>Another option other than Response.Write would be to write XHtml with <a href=\"http://weblogs.asp.net/jigardesai/archive/2008/02/08/xslt-transformation-in-asp-net-mvc-framework.aspx\" rel=\"nofollow noreferrer\">XSL transformations</a></p>\n"
},
{
"answer_id": 24130947,
"author": "KurvaBG",
"author_id": 3724124,
"author_profile": "https://Stackoverflow.com/users/3724124",
"pm_score": 1,
"selected": false,
"text": "<p>My answer is based on personal XP with MVC4 cshtml - you can use:\n <code>@Html.Raw(\"SomeStringDirectlyInsideTheBrowserPageHTMLCode\")</code></p>\n\n<p>This renders the (dynamic) string at its position unlike <code>Response.Write(MyString)</code> which as far as I've noticed always renders the string at the begining of the browser-page.</p>\n\n<p>Note that the HTML tags rendered by <code>@Html.Raw(MyString)</code> cannot be checked by the compiler. I mean: @Html.Raw(\"<div ....>\") cannot be closed by mere </div> because you will get an error (<div ....> is not detected by the compiler) so you must close the tag with @Html.Raw(\"</div>\")</p>\n\n<p>P.S.<br/>In some cases this doesn't work (for example it fails within DevExpress) - use <code>ViewContext.Writer.Write()</code> or <code>ViewContext.Writer.WriteLine()</code> instead.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425/"
] |
With ASP.NET's view engine/template aspx/ashx pages the way to spit to screen seems to be:
```
<%= Person.Name %>
```
Which was fine with webforms as alot of model data was bound to controls programatically. But with MVC we are now using this syntax more oftern.
The issue I have with it is quite trivial, but annoying either way. This is that it seems to break up the mark up i.e.:
```
<% foreach(var Person in People) { %>
<%= Person.Name %>
<% } %>
```
That seems like alot of opening and closing tags to me!
Other view engines in the MVC contrib have a means of spitting to screen with out opening and closing the script tags using standard keyword such as "print, out, echo" i.e. (brail example):
```
<%
for element in list:
output "<li>${element}</li>"
end
%>
```
Now, I said this may seem trivial, but it just seems more readable this way. So what are the advantages of MS having this syntax, and not providing a output method?
Cheers, Chris.
|
Consider something like this, instead:
```
<% foreach(var Person in People) {
Response.Write(Person.Name);
} %>
```
I believe that'll work. (Although I haven't tested it; I've only just begun with MVC and don't have the toolset here at the office.)
EDIT: I apparently missed the actual question ... :)
Microsoft does provide an output method, but didn't provide a syntax like the one you describe. The output method is `Response.Write()`. I can't answer this directly (I believe you'll need to check with Scott Hanselmann over at MS :)), but I think they didn't want to complicate scripting by adding yet-another-language for us to learn; I think they wanted to leverage the languages (C#, VB, etc.) which developers already knew.
EDIT #2: I placed the following in a comment, and in retrospect (for completeness), it should be part of the answer.
If you head over to the [Learn MVC site on ASP.NET](http://www.asp.net/learn/mvc/tutorial-04-cs.aspx), in the view tutorial (that's the link), you'll see the following paragraph:
>
> Since you call `Response.Write()` so
> often, Microsoft provides you with a
> shortcut for calling the
> `Response.Write()` method. The view in
> Listing 3 uses the delimiters `<%=` and
> `%>` as a shortcut for calling
> `Response.Write()`.
>
>
>
Essentially, `<%= %>` is the accepted shortcut for `Response.Write`, and you therefore can use the full `Response.Write` method anywhere you'd use `<%= %>`.
|
197,649 |
<p>While working on SVG implementation for Internet Explorer to be based on its own VML format I came to a problem of translation of an SVG elliptical arc to an VML elliptical arc.</p>
<p>In VML an arc is given by: two angles for two points on ellipse and lengths of radiuses,
In SVG an arc is given by: two pairs of coordinates for two points on ellipse and sizes of ellipse boundary box</p>
<p>So, the question is: How to express angles of two points on ellipse to two pairs of their coordinates.
An intermediate question could be: How to find the center of an ellipse by coordinates of a pair of points on its curve.</p>
<p><b>Update</b>: Let's have a precondition saying that an ellipse is normally placed (its radiuses are parallel to linear coordinate system axis), thus no rotation is applied.</p>
<p><b>Update</b>: This question is not related to svg:ellipse element, rather to "a" elliptical arc command in svg:path element (<a href="http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands" rel="noreferrer">SVG Paths: The elliptical arc curve commands</a>)</p>
|
[
{
"answer_id": 197664,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>An ellipse cannot be defined by only two points. Even a circle (a special cased ellipse) is defined by three points.</p>\n\n<p>Even with three points, you would have infinite ellipses passing through these three points (think: rotation).</p>\n\n<p>Note that a bounding box suggests a center for the ellipse, and most probably assumes that its major and minor axes are parallel to the x,y (or y,x) axes.</p>\n"
},
{
"answer_id": 197671,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 1,
"selected": false,
"text": "<p>The intermediate question is fairly easy... you don't. You work out the centre of an ellipse from the bounding box (namely, the centre of the box is the centre of the ellipse, as long as the ellipse is centred in the box).</p>\n\n<p>For your first question, I'd look at the polar form of the ellipse equation, which is available on <a href=\"http://en.wikipedia.org/wiki/Ellipse\" rel=\"nofollow noreferrer\">Wikipedia</a>. You would need to work out the eccentricity of the ellipse as well.</p>\n\n<p>Or you could brute force the values from the bounding box... work out if a point lies on the ellipse and matches the angle, and iterate through every point in the bounding box.</p>\n"
},
{
"answer_id": 198137,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 6,
"selected": true,
"text": "<p>So the solution is here:</p>\n\n<p>The parametrized formula of an ellipse:</p>\n\n<pre>\nx = x0 + a * cos(t)\ny = y0 + b * sin(t)\n</pre>\n\n<p>Let's put known coordinates of two points to it:</p>\n\n<pre>\nx1 = x0 + a * cos(t1)\nx2 = x0 + a * cos(t2)\ny1 = y0 + b * sin(t1)\ny2 = y0 + b * sin(t2)\n</pre>\n\n<p>Now we have a system of equations with 4 variables: center of ellipse (x0/y0) and two angles t1, t2</p>\n\n<p>Let's subtract equations in order to get rid of center coordinates:</p>\n\n<pre>\nx1 - x2 = a * (cos(t1) - cos(t2))\ny1 - y2 = b * (sin(t1) - sin(t2))\n</pre>\n\n<p>This can be rewritten (with product-to-sum identities formulas) as:</p>\n\n<pre>\n(x1 - x2) / (2 * a) = sin((t1 + t2) / 2) * sin((t1 - t2) / 2)\n(y2 - y1) / (2 * b) = cos((t1 + t2) / 2) * sin((t1 - t2) / 2)\n</pre>\n\n<p>Let's replace some of the equations:</p>\n\n<pre>\nr1: (x1 - x2) / (2 * a)\nr2: (y2 - y1) / (2 * b)\na1: (t1 + t2) / 2\na2: (t1 - t2) / 2\n</pre>\n\n<p>Then we get simple equations system:</p>\n\n<pre>\nr1 = sin(a1) * sin(a2)\nr2 = cos(a1) * sin(a2)\n</pre>\n\n<p>Dividing first equation by second produces:</p>\n\n<pre>\na1 = arctan(r1/r2)\n</pre>\n\n<p>Adding this result to the first equation gives:</p>\n\n<pre>\na2 = arcsin(r2 / cos(arctan(r1/r2)))\n</pre>\n\n<p>Or, simple (using compositions of trig and inverse trig functions):</p>\n\n<pre>\na2 = arcsin(r2 / (1 / sqrt(1 + (r1/r2)^2)))\n</pre>\n\n<p>or even more simple:</p>\n\n<pre>\na2 = arcsin(sqrt(r1^2 + r2^2))\n</pre>\n\n<p>Now the initial four-equations system can be resolved with easy and all angles as well as eclipse center coordinates can be found.</p>\n"
},
{
"answer_id": 11467200,
"author": "Rikki",
"author_id": 829305,
"author_profile": "https://Stackoverflow.com/users/829305",
"pm_score": 3,
"selected": false,
"text": "<p>The elliptical curve arc link you posted includes a <a href=\"http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes\" rel=\"noreferrer\">link to elliptical arc implementation notes</a>.</p>\n\n<p>In there, you will find the equations for <a href=\"http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter\" rel=\"noreferrer\">conversion from endpoint to centre parameterisation</a>.</p>\n\n<p>Here is my JavaScript implementation of those equations, taken from <a href=\"http://users.ecs.soton.ac.uk/rfp07r/interactive-svg-examples/arc.html\" rel=\"noreferrer\">an interactive demo of elliptical arc paths</a>, using <a href=\"http://sylvester.jcoglan.com/\" rel=\"noreferrer\">Sylvester.js</a> to perform the matrix and vector calculations.</p>\n\n<pre><code>// Calculate the centre of the ellipse\n// Based on http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter\nvar x1 = 150; // Starting x-point of the arc\nvar y1 = 150; // Starting y-point of the arc\nvar x2 = 400; // End x-point of the arc\nvar y2 = 300; // End y-point of the arc\nvar fA = 1; // Large arc flag\nvar fS = 1; // Sweep flag\nvar rx = 100; // Horizontal radius of ellipse\nvar ry = 50; // Vertical radius of ellipse\nvar phi = 0; // Angle between co-ord system and ellipse x-axes\n\nvar Cx, Cy;\n\n// Step 1: Compute (x1′, y1′)\nvar M = $M([\n [ Math.cos(phi), Math.sin(phi)],\n [-Math.sin(phi), Math.cos(phi)]\n ]);\nvar V = $V( [ (x1-x2)/2, (y1-y2)/2 ] );\nvar P = M.multiply(V);\n\nvar x1p = P.e(1); // x1 prime\nvar y1p = P.e(2); // y1 prime\n\n\n// Ensure radii are large enough\n// Based on http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters\n// Step (a): Ensure radii are non-zero\n// Step (b): Ensure radii are positive\nrx = Math.abs(rx);\nry = Math.abs(ry);\n// Step (c): Ensure radii are large enough\nvar lambda = ( (x1p * x1p) / (rx * rx) ) + ( (y1p * y1p) / (ry * ry) );\nif(lambda > 1)\n{\n rx = Math.sqrt(lambda) * rx;\n ry = Math.sqrt(lambda) * ry;\n}\n\n\n// Step 2: Compute (cx′, cy′)\nvar sign = (fA == fS)? -1 : 1;\n// Bit of a hack, as presumably rounding errors were making his negative inside the square root!\nif((( (rx*rx*ry*ry) - (rx*rx*y1p*y1p) - (ry*ry*x1p*x1p) ) / ( (rx*rx*y1p*y1p) + (ry*ry*x1p*x1p) )) < 1e-7)\n var co = 0;\nelse\n var co = sign * Math.sqrt( ( (rx*rx*ry*ry) - (rx*rx*y1p*y1p) - (ry*ry*x1p*x1p) ) / ( (rx*rx*y1p*y1p) + (ry*ry*x1p*x1p) ) );\nvar V = $V( [rx*y1p/ry, -ry*x1p/rx] );\nvar Cp = V.multiply(co);\n\n// Step 3: Compute (cx, cy) from (cx′, cy′)\nvar M = $M([\n [ Math.cos(phi), -Math.sin(phi)],\n [ Math.sin(phi), Math.cos(phi)]\n ]);\nvar V = $V( [ (x1+x2)/2, (y1+y2)/2 ] );\nvar C = M.multiply(Cp).add(V);\n\nCx = C.e(1);\nCy = C.e(2);\n</code></pre>\n"
},
{
"answer_id": 61169127,
"author": "Ievgen",
"author_id": 508330,
"author_profile": "https://Stackoverflow.com/users/508330",
"pm_score": 0,
"selected": false,
"text": "<p>TypeScript implementation based on the answer from Rikki. </p>\n\n<p>Default DOMMatrix and DOMPoint are used for the calculations (Tested in the latest Chrome v.80) instead of the external library.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> ellipseCenter(\r\n x1: number,\r\n y1: number,\r\n rx: number,\r\n ry: number,\r\n rotateDeg: number,\r\n fa: number,\r\n fs: number,\r\n x2: number,\r\n y2: number\r\n ): DOMPoint {\r\n const phi = ((rotateDeg % 360) * Math.PI) / 180;\r\n const m = new DOMMatrix([\r\n Math.cos(phi),\r\n -Math.sin(phi),\r\n Math.sin(phi),\r\n Math.cos(phi),\r\n 0,\r\n 0,\r\n ]);\r\n let v = new DOMPoint((x1 - x2) / 2, (y1 - y2) / 2).matrixTransform(m);\r\n const x1p = v.x;\r\n const y1p = v.y;\r\n rx = Math.abs(rx);\r\n ry = Math.abs(ry);\r\n const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);\r\n if (lambda > 1) {\r\n rx = Math.sqrt(lambda) * rx;\r\n ry = Math.sqrt(lambda) * ry;\r\n }\r\n const sign = fa === fs ? -1 : 1;\r\n const div =\r\n (rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p) /\r\n (rx * rx * y1p * y1p + ry * ry * x1p * x1p);\r\n\r\n const co = sign * Math.sqrt(Math.abs(div));\r\n\r\n // inverse matrix b and c\r\n m.b *= -1;\r\n m.c *= -1;\r\n v = new DOMPoint(\r\n ((rx * y1p) / ry) * co,\r\n ((-ry * x1p) / rx) * co\r\n ).matrixTransform(m);\r\n v.x += (x1 + x2) / 2;\r\n v.y += (y1 + y2) / 2;\r\n return v;\r\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 71913472,
"author": "NoBullsh1t",
"author_id": 8447743,
"author_profile": "https://Stackoverflow.com/users/8447743",
"pm_score": 0,
"selected": false,
"text": "<p>Answering part of the question with code</p>\n<blockquote>\n<p>How to find the center of an ellipse by coordinates of a pair of points on its curve.</p>\n</blockquote>\n<p>This is a TypeScript function which is based on the excellent accepted answer by Sergey Illinsky above (which ends somewhat halfway through, IMHO). It calculates the center of an ellipse with given radii, given the condition that both provided points <code>a</code> and <code>b</code> must lie on the circumference of the ellipse. Since there are (almost) always two solutions to this problem, the code choses the solution that places the ellipse "above" the two points:</p>\n<p>(Note that the ellipse must have major and minor axis parallel to the horizontal/vertical)</p>\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * We're in 2D, so that's what our vertors look like\n */\nexport type Point = [number, number];\n\n/**\n * Calculates the vector that connects the two points\n */\nfunction deltaXY (from: Point, to: Point): Point {\n return [to[0]-from[0], to[1]-from[1]];\n}\n\n/**\n * Calculates the sum of an arbitrary amount of vertors\n */\nfunction vecAdd (...vectors: Point[]): Point {\n return vectors.reduce((acc, curr) => [acc[0]+curr[0], acc[1]+curr[1]], [0, 0]);\n}\n\n/**\n * Given two points a and b, as well as ellipsis radii rX and rY, this \n * function calculates the center-point of the ellipse, so that it\n * is "above" the two points and has them on the circumference\n */\nfunction topLeftOfPointsCenter (a: Point, b: Point, rX: number, rY: number): Point {\n const delta = deltaXY(a, b);\n \n // Sergey's work leads up to a simple system of liner equations. \n // Here, we calculate its general solution for the first of the two angles (t1)\n const A = Math.asin(Math.sqrt((delta[0]/(2*rX))**2+(delta[1]/(2*rY))**2));\n const B = Math.atan(-delta[0]/delta[1] * rY/rX);\n const alpha = A + B;\n \n // This may be the new center, but we don't know to which of the two\n // solutions it belongs, yet\n let newCenter = vecAdd(a, [\n rX * Math.cos(alpha),\n rY * Math.sin(alpha)\n ]);\n\n // Figure out if it is the correct solution, and adjusting if not\n const mean = vecAdd(a, [delta[0] * 0.5, delta[1] * 0.5]);\n const factor = mean[1] > newCenter[1] ? 1 : -1;\n const offMean = deltaXY(mean, newCenter);\n newCenter = vecAdd(mean, [offMean[0] * factor, offMean[1] * factor]);\n\n return newCenter;\n}\n</code></pre>\n<p>This function does <strong>not</strong> check if a solution is possible, meaning whether the radii provided are large enough to even connect the two points!</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23815/"
] |
While working on SVG implementation for Internet Explorer to be based on its own VML format I came to a problem of translation of an SVG elliptical arc to an VML elliptical arc.
In VML an arc is given by: two angles for two points on ellipse and lengths of radiuses,
In SVG an arc is given by: two pairs of coordinates for two points on ellipse and sizes of ellipse boundary box
So, the question is: How to express angles of two points on ellipse to two pairs of their coordinates.
An intermediate question could be: How to find the center of an ellipse by coordinates of a pair of points on its curve.
**Update**: Let's have a precondition saying that an ellipse is normally placed (its radiuses are parallel to linear coordinate system axis), thus no rotation is applied.
**Update**: This question is not related to svg:ellipse element, rather to "a" elliptical arc command in svg:path element ([SVG Paths: The elliptical arc curve commands](http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands))
|
So the solution is here:
The parametrized formula of an ellipse:
```
x = x0 + a * cos(t)
y = y0 + b * sin(t)
```
Let's put known coordinates of two points to it:
```
x1 = x0 + a * cos(t1)
x2 = x0 + a * cos(t2)
y1 = y0 + b * sin(t1)
y2 = y0 + b * sin(t2)
```
Now we have a system of equations with 4 variables: center of ellipse (x0/y0) and two angles t1, t2
Let's subtract equations in order to get rid of center coordinates:
```
x1 - x2 = a * (cos(t1) - cos(t2))
y1 - y2 = b * (sin(t1) - sin(t2))
```
This can be rewritten (with product-to-sum identities formulas) as:
```
(x1 - x2) / (2 * a) = sin((t1 + t2) / 2) * sin((t1 - t2) / 2)
(y2 - y1) / (2 * b) = cos((t1 + t2) / 2) * sin((t1 - t2) / 2)
```
Let's replace some of the equations:
```
r1: (x1 - x2) / (2 * a)
r2: (y2 - y1) / (2 * b)
a1: (t1 + t2) / 2
a2: (t1 - t2) / 2
```
Then we get simple equations system:
```
r1 = sin(a1) * sin(a2)
r2 = cos(a1) * sin(a2)
```
Dividing first equation by second produces:
```
a1 = arctan(r1/r2)
```
Adding this result to the first equation gives:
```
a2 = arcsin(r2 / cos(arctan(r1/r2)))
```
Or, simple (using compositions of trig and inverse trig functions):
```
a2 = arcsin(r2 / (1 / sqrt(1 + (r1/r2)^2)))
```
or even more simple:
```
a2 = arcsin(sqrt(r1^2 + r2^2))
```
Now the initial four-equations system can be resolved with easy and all angles as well as eclipse center coordinates can be found.
|
197,675 |
<pre><code>Foo* set = new Foo[100];
// ...
delete [] set;
</code></pre>
<p>You don't pass the array's boundaries to <code>delete[]</code>. But where is that information stored? Is it standardised?</p>
|
[
{
"answer_id": 197689,
"author": "jeffm",
"author_id": 1544,
"author_profile": "https://Stackoverflow.com/users/1544",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't something that's in the spec -- it's implementation dependent.</p>\n"
},
{
"answer_id": 197698,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Because the array to be 'deleted' should have been created with a single use of the 'new' operator. The 'new' operation should have put that information on the heap. Otherwise, how would additional uses of new know where the heap ends?</p>\n"
},
{
"answer_id": 197699,
"author": "Peter Kühne",
"author_id": 27351,
"author_profile": "https://Stackoverflow.com/users/27351",
"pm_score": 9,
"selected": true,
"text": "<p>When you allocate memory on the heap, your allocator will keep track of how much memory you have allocated. This is usually stored in a \"head\" segment just before the memory that you get allocated. That way when it's time to free the memory, the de-allocator knows exactly how much memory to free.</p>\n"
},
{
"answer_id": 197706,
"author": "Andre",
"author_id": 17650,
"author_profile": "https://Stackoverflow.com/users/17650",
"pm_score": -1,
"selected": false,
"text": "<p>It is not standardized. In Microsoft's runtime the new operator uses malloc() and the delete operator uses free(). So, in this setting your question is equivalent to the following: How does free() know the size of the block?</p>\n\n<p>There is some bookkeeping going on behind the scenes, i.e. in the C runtime.</p>\n"
},
{
"answer_id": 197716,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 4,
"selected": false,
"text": "<p>The information is not standardised. However in the platforms that I have worked on this information is stored in memory just before the first element. Therefore you could theoretically access it and inspect it, however it's not worth it.</p>\n\n<p>Also this is why you must use delete [] when you allocated memory with new [], as the array version of delete knows that (and where) it needs to look to free the right amount of memory - and call the appropriate number of destructors for the objects.</p>\n"
},
{
"answer_id": 206355,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 3,
"selected": false,
"text": "<p>It's defined in the C++ standard to be compiler specific. Which means compiler magic. It can break with non-trivial alignment restrictions on at least one major platform.</p>\n\n<p>You can think about possible implementations by realizing that <code>delete[]</code> is only defined for pointers returned by <code>new[]</code>, which may not be the same pointer as returned by <code>operator new[]</code>. One implementation in the wild is to store the array count in the first int returned by <code>operator new[]</code>, and have <code>new[]</code> return a pointer offset past that. (This is why non-trivial alignments can break <code>new[]</code>.)</p>\n\n<p>Keep in mind that <code>operator new[]/operator delete[]</code>!=<code>new[]/delete[]</code>.</p>\n\n<p>Plus, this is orthogonal to how C knows the size of memory allocated by <code>malloc</code>. </p>\n"
},
{
"answer_id": 206407,
"author": "Francisco Soto",
"author_id": 3695,
"author_profile": "https://Stackoverflow.com/users/3695",
"pm_score": 3,
"selected": false,
"text": "<p>Basically its arranged in memory as:</p>\n\n<p>[info][mem you asked for...]</p>\n\n<p>Where info is the structure used by your compiler to store the amount of memory allocated, and what not.</p>\n\n<p>This is implementation dependent though.</p>\n"
},
{
"answer_id": 21984370,
"author": "Avt",
"author_id": 3140927,
"author_profile": "https://Stackoverflow.com/users/3140927",
"pm_score": 5,
"selected": false,
"text": "<p>ONE OF THE approaches for compilers is to allocate a little more memory and to store a count of elements in a head element. </p>\n\n<p>Example how it could be done:</p>\n\n<p>Here</p>\n\n<pre><code>int* i = new int[4];\n</code></pre>\n\n<p>compiler will allocate <code>sizeof(int)*5</code> bytes.</p>\n\n<pre><code>int *temp = malloc(sizeof(int)*5)\n</code></pre>\n\n<p>Will store \"4\" in the first <code>sizeof(int)</code> bytes</p>\n\n<pre><code>*temp = 4;\n</code></pre>\n\n<p>and set <code>i</code></p>\n\n<pre><code>i = temp + 1;\n</code></pre>\n\n<p>So <code>i</code> will points to an array of 4 elements, not 5.</p>\n\n<p>And deletion</p>\n\n<pre><code>delete[] i;\n</code></pre>\n\n<p>will be processed in the following way:</p>\n\n<pre><code>int *temp = i - 1;\nint numbers_of_element = *temp; // = 4\n... call destructor for numbers_of_element elements\n... that are stored in temp + 1, temp + 2, ... temp + 4 if needed\nfree (temp)\n</code></pre>\n"
},
{
"answer_id": 33708246,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": 1,
"selected": false,
"text": "<p>This is a more interesting problem than you might think at first. This reply is about one possible implementation.</p>\n\n<p>Firstly, while at some level your system has to know how to 'free' the memory block, the underlying malloc/free (which new/delete/new[]/delete[] generally call) don't always remember exactly how much memory you ask for, it can get rounded up (for example, once you are above 4K it is often rounded up to the next 4K-sized block).</p>\n\n<p>Therefore, even if could get the size of the memory block, that doesn't tell us how many values are in the new[]ed memory, as it can be smaller. Therefore, we do have to store an extra integer telling us how many values there are.</p>\n\n<p>EXCEPT, if the type being constructed doesn't have a destructor, then delete[] doesn't have to do anything except free the memory block, and therefore doesn't have to store anything!</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4833/"
] |
```
Foo* set = new Foo[100];
// ...
delete [] set;
```
You don't pass the array's boundaries to `delete[]`. But where is that information stored? Is it standardised?
|
When you allocate memory on the heap, your allocator will keep track of how much memory you have allocated. This is usually stored in a "head" segment just before the memory that you get allocated. That way when it's time to free the memory, the de-allocator knows exactly how much memory to free.
|
197,678 |
<p>I want to do some checking in a writer accessor. My first idea was returning a boolean.</p>
<pre><code>class MyClass
def var=(var)
@var = var
# some checking
return true
end
end
m = MyClass.new
retval = (m.var = 'foo')
=> "foo"
</code></pre>
<p>Can I set a return value in a writer accessor? If yes, how can I get this value?</p>
|
[
{
"answer_id": 197704,
"author": "epochwolf",
"author_id": 16204,
"author_profile": "https://Stackoverflow.com/users/16204",
"pm_score": 3,
"selected": false,
"text": "<p>I would use set_var(var) instead of what you are trying to do, an attribute writer is assumed to just work. What you are trying to do is nonstandard and non-obvious to the next poor person to use your code. (It may just be yourself) I would throw an exception if bad input is sent or something rather exceptional happens. </p>\n\n<p>You want this behavior</p>\n\n<pre><code>Correct\n>>temp = object.var = 7\n=> 7 \n\nWrong\n>>temp = object.var = 7\n=> false\n</code></pre>\n\n<p>The = operator should always return the value that was passed to it. Ruby uses implicit returns which is uncommon in programming languages. Double check the returns when you use <code>method=()</code>. </p>\n"
},
{
"answer_id": 197724,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 2,
"selected": false,
"text": "<p>Also, per your example, to clean things up you could do the following:</p>\n\n<pre><code>class MyClass\n attr_accessor :var\nend\n\nm = MyClass.new\nm.var = \"Test\"\nputs m.var # => \"Test\"\n</code></pre>\n\n<p>In regards to your question though, are you asking if you can return a value other than what you set for the value of the object?</p>\n\n<p><b>Update</b></p>\n\n<p>Check out this project: <a href=\"http://validatable.rubyforge.org/\" rel=\"nofollow noreferrer\">Validatable</a>. It adds ActiveRecord like validations to your class attributes.</p>\n\n<p>Quick scenario:</p>\n\n<pre><code>class Person\n include Validatable\n validates_presence_of :name\n attr_accessor :name\nend\n\nclass PersonPresenter\n include Validatable\n include_validations_for :person\n attr_accessor :person\n\n def initialize(person)\n @person = person\n end\nend\n\npresenter = PersonPresenter.new(Person.new)\npresenter.valid? #=> false\npresenter.errors.on(:name) #=> \"can't be blank\"\n</code></pre>\n"
},
{
"answer_id": 197812,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class Test\n def var=(var)\n @var = var\n return true\n end\nend\n\nt1, t2 = Test.new, Test.new\n\nt1.var = 123 # evaluates to 123\n\n# Why is it impossible to return something else:\nt1.var = t2.var = 456\n</code></pre>\n\n<p>As stated in the comment: I believe it's impossible to change the return value in order to allow chained assignments. Changing the return value would probably be unexpected by the majority of Ruby programmers anyway.</p>\n\n<p>Disclaimer: I tested the code above but I've found no explicit references to verify my statement.</p>\n\n<p><strong>Update</strong></p>\n\n<pre><code>class Test\n def method_missing(method, *args)\n if method == :var=\n # check something\n @var = args[0]\n return true\n else\n super(method, *args)\n end\n end\n\n def var\n @var\n end\nend\n\nt = Test.new\nt.var = 123 # evaluates to 123\nt.does_not_exists # NoMethodError\n</code></pre>\n\n<p>It really seems to impossible! The above sample suggests that the return value <strong>isn't related to the <code>var=</code> method</strong> at all. You cannot change this behavior - it's the fundamental way how Ruby assignments work.</p>\n\n<p><strong>Update 2: Solution found</strong></p>\n\n<p>You could raise an exception!</p>\n\n<pre><code>class Test\n def var=(var)\n raise ArgumentError if var < 100 # or some other condition\n @var = var\n end\n def var\n @var\n end\nend\n\nt = Test.new\nt.var = 123 # 123\nt.var = 1 # ArgumentError raised\nt.var # 123\n</code></pre>\n"
},
{
"answer_id": 4457027,
"author": "Jon Kern",
"author_id": 344720,
"author_profile": "https://Stackoverflow.com/users/344720",
"pm_score": 1,
"selected": false,
"text": "<p><em>I know this is a late response to the party...</em></p>\n\n<p>It's hard to know what you are attempting to do with the class. You mentioned wanting to check it before saving... to a database? file?</p>\n\n<p>What would you like to happen in the case of a bad attribute value? </p>\n\n<p>By using a boolean return, you effectively \"hide\" the error (because you <em>will</em> forget about the weird thing of having to check the return value of a setter).</p>\n\n<p>While you can do what others suggested</p>\n\n<ul>\n<li>Use Validator plugin </li>\n<li>Raise an error</li>\n</ul>\n\n<p>You can also consider an isValid? method like many classes that end up getting persisted do. Then the save can check the state of the object and throw an error.</p>\n\n<p><strong>Bottom line:</strong></p>\n\n<ul>\n<li>Don't do what you posted</li>\n<li>Do throw an error (by any of the posted solutions) </li>\n</ul>\n\n<p>One way to help drive the solution is to consider writing the behavior you are looking for first (i.e., <strong>BDD</strong>). Then, work your way further into what the class should do by <strong>TDD</strong> -ing using <strong>RSpec</strong> to get the desired class \"contract\" that needs to emerge to support the desired behavior.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341/"
] |
I want to do some checking in a writer accessor. My first idea was returning a boolean.
```
class MyClass
def var=(var)
@var = var
# some checking
return true
end
end
m = MyClass.new
retval = (m.var = 'foo')
=> "foo"
```
Can I set a return value in a writer accessor? If yes, how can I get this value?
|
I would use set\_var(var) instead of what you are trying to do, an attribute writer is assumed to just work. What you are trying to do is nonstandard and non-obvious to the next poor person to use your code. (It may just be yourself) I would throw an exception if bad input is sent or something rather exceptional happens.
You want this behavior
```
Correct
>>temp = object.var = 7
=> 7
Wrong
>>temp = object.var = 7
=> false
```
The = operator should always return the value that was passed to it. Ruby uses implicit returns which is uncommon in programming languages. Double check the returns when you use `method=()`.
|
197,712 |
<pre><code>echo "<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm(\'are you sure you wish to delete this record\');'>delete</a></td>";
</code></pre>
<p>Above is the code I am trying to use. Every time it does nothing and I cannot see how I can use 'proper' JavaScript methods. What is the reason?</p>
|
[
{
"answer_id": 197723,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 1,
"selected": false,
"text": "<pre><code>echo \"<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm(&quot;are you sure you wish to delete this record&quot;);'>delete</a></td>\";\n</code></pre>\n\n<p>Use Firefox's HTML syntax highlighting to your advantage. :-)</p>\n"
},
{
"answer_id": 197745,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 2,
"selected": false,
"text": "<p>It is also a bad idea to use GET methods to change state - take a look at the guidelines on when to use GET and when to use POST ( <a href=\"http://www.w3.org/2001/tag/doc/whenToUseGet.html#checklist\" rel=\"nofollow noreferrer\">http://www.w3.org/2001/tag/doc/whenToUseGet.html#checklist</a> )</p>\n"
},
{
"answer_id": 197749,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 2,
"selected": false,
"text": "<p>I think $row[id] is not evaluating correctly in your echo statement. Try this:</p>\n\n<pre><code>echo \"<td><a href='delete.php?id={$row[id]}&&category=$a'...\n</code></pre>\n\n<p>Note the squiggly brackets.</p>\n\n<p>But THIS is much easier to read:</p>\n\n<pre><code>?><td><a href=\"delete.php?id=<?=$row[id];?>&amp;category=<?=$a;?>\" onclick=\"return confirm('are you sure you wish to delete this record');\">delete</a></td><?\n</code></pre>\n\n<p>As an aside, add a function to your js for handling the confirmation:</p>\n\n<pre><code>function confirm_delete() {\n return confirm('Are you sure you want to delete this record?');\n}\n</code></pre>\n\n<p>Then your onclick method can just be <code>return confirm_delete()</code>.</p>\n"
},
{
"answer_id": 197960,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": -1,
"selected": false,
"text": "<p>And if you insist on using the echo-thing:</p>\n\n<pre><code>echo \"<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm(\\\\'are you sure you wish to delete this record\\\\');'>delete</a></td>\";\n</code></pre>\n\n<p>-- because the escaping is treated from the php-interpretator !-)</p>\n"
},
{
"answer_id": 198319,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "<p>Another solution:</p>\n\n<pre><code>echo '<td><a href=\"delete.php?id=' . $row[id] . '&category=' . $a . '\" onclick=\"return confirm(\\'are you sure you wish to delete this record?\\');'>delete</a></td>';\n</code></pre>\n\n<p>I changed the double quotes to single quotes and vise versa. I then concatinated the variables so there is no evaluation needed by PHP.</p>\n\n<p>Also, I'm not sure if the return on the onclick will actually stop the link from being \"clicked\" when the user clicks no.</p>\n"
},
{
"answer_id": 199345,
"author": "Brad",
"author_id": 26130,
"author_profile": "https://Stackoverflow.com/users/26130",
"pm_score": -1,
"selected": false,
"text": "<p>Here is what I use for the same type of thing.</p>\n\n<p>I do not echo/print it, I will put the html between ?> html \n\n<pre><code>?> <td><a href=\"?mode=upd&id=<?= $row[id] ?>&table=<?= $table ?>\">Upd</a> / <a href=\"?mode=del&id=<?= $row[id] ?>&table=<?= $table ?>\" onclick=\"return confirm('Are you sure you want to delete?')\">Del</a></td> <?php\n</code></pre>\n"
},
{
"answer_id": 199530,
"author": "cole",
"author_id": 910,
"author_profile": "https://Stackoverflow.com/users/910",
"pm_score": 2,
"selected": false,
"text": "<p>Just a suggestion, are you using a framework?</p>\n\n<p>I use MooTools then simply include this script in the HTML</p>\n\n<p>confirm_delete.js </p>\n\n<pre><code>window.addEvent('domready', function(){\n $$('a.confirm_delete').each(function(item, index){\n item.addEvent('click', function(){\n var confirm_result = confirm('Sure you want to delete');\n if(confirm_result){\n this.setProperty('href', this.getProperty('href') + '&confirm');\n return true;\n }else{\n return false;\n }\n }); \n });\n});\n</code></pre>\n\n<p>All it does is find any \"a\" tags with class=\"confirm_delete\" and attaches the same code as your script but i find it easier to use. It also adds a confirmation variable to the address so that if JavaScript is turned off you can still send them to a screen with a confirmation prompt.</p>\n"
},
{
"answer_id": 199580,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>You should try to separate your JavaScript from your HTML as much as possible. Output the vanilla HTML initially and then add the event to the link afterwards.</p>\n\n<pre><code>printf('<td><a id=\"deleteLink\" href=\"delete.php?id=%d&amp;category=%s\">Delete</a></td>', $row[\"id\"], $a);\n</code></pre>\n\n<p>And then some JavaScript code somewhere on the page:</p>\n\n<pre><code>document.getElementById('deleteLink').onclick = function() {\n return confirm(\"Are you sure you wish to delete?\");\n};\n</code></pre>\n\n<p>From your example however, it looks like you've probably got a table with multiple rows, each with its own delete link. That makes using this style even more attractive, since you won't be outputting the <code>confirm(...)</code> text over and over.</p>\n\n<p>If this is the case, you obviously can't use an <code>id</code> on the link, so it's probably better to use a class. <code><a class=\"deleteLink\" ...</code></p>\n\n<p>If you were using a JavaScript library, such as jQuery, this is very easy:</p>\n\n<pre><code>$('.deleteLink').click(function() {\n return confirm(\"...\");\n});\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
echo "<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm(\'are you sure you wish to delete this record\');'>delete</a></td>";
```
Above is the code I am trying to use. Every time it does nothing and I cannot see how I can use 'proper' JavaScript methods. What is the reason?
|
It is also a bad idea to use GET methods to change state - take a look at the guidelines on when to use GET and when to use POST ( <http://www.w3.org/2001/tag/doc/whenToUseGet.html#checklist> )
|
197,720 |
<p>I am importing the CreateICeeFileGen() function from the unmanaged DLL mscorpe.dll in a C# application, in order to generate a PE file. This function returns a pointer to an C++ object <a href="http://msdn.microsoft.com/en-us/library/ms404463.aspx" rel="nofollow noreferrer">defined here</a>, is there any way I can access fields from this class via C# or do I need to write an unmanaged wrapper DLL?</p>
<p>The code I'm using currently is as follows:-</p>
<pre><code>[DllImport(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorpe.dll", EntryPoint = "CreateICeeFileGen")]
static extern void CreateICeeFileGen(out IntPtr iceeFileGenPointer);
...
IntPtr filePtr;
CreateICeeFileGen(out filePtr);
</code></pre>
<p><strong>N.B.</strong>: I know you can do similar things with .net libraries but I need to use unmanaged libraries for my purposes.</p>
|
[
{
"answer_id": 197736,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": true,
"text": "<p>You need a wrapper library to be able to use the class from C#. </p>\n\n<p>The best bet would be to create the wrapper using C++/CLI, which can directly call the unmanaged function and expose the details with a managed class. This will eliminate the need to use P/Invoke for anything.</p>\n\n<p>(Well, technically if you know the class layout you could mess around with pointer arithmetic to access the fields, but this would be very fragile and messy, and trying to call virtual functions in this way would be extremely ugly).</p>\n"
},
{
"answer_id": 197751,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like COM class/interface. Can you not just use COM instead?</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
I am importing the CreateICeeFileGen() function from the unmanaged DLL mscorpe.dll in a C# application, in order to generate a PE file. This function returns a pointer to an C++ object [defined here](http://msdn.microsoft.com/en-us/library/ms404463.aspx), is there any way I can access fields from this class via C# or do I need to write an unmanaged wrapper DLL?
The code I'm using currently is as follows:-
```
[DllImport(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorpe.dll", EntryPoint = "CreateICeeFileGen")]
static extern void CreateICeeFileGen(out IntPtr iceeFileGenPointer);
...
IntPtr filePtr;
CreateICeeFileGen(out filePtr);
```
**N.B.**: I know you can do similar things with .net libraries but I need to use unmanaged libraries for my purposes.
|
You need a wrapper library to be able to use the class from C#.
The best bet would be to create the wrapper using C++/CLI, which can directly call the unmanaged function and expose the details with a managed class. This will eliminate the need to use P/Invoke for anything.
(Well, technically if you know the class layout you could mess around with pointer arithmetic to access the fields, but this would be very fragile and messy, and trying to call virtual functions in this way would be extremely ugly).
|
197,725 |
<p>I'm writing an winforms app that needs to set internet explorer's proxy settings and then open a new browser window. At the moment, I'm applying the proxy settings by going into the registry:</p>
<pre><code>RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", "127.0.0.1:8080");
</code></pre>
<p>Is going into the registry the <em>best</em> way to do this, or is there a more recommended approach? I'd like to avoid registry changes if there's an alternative solution.</p>
|
[
{
"answer_id": 197985,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "<p>Check out this KB article specifically tagged at what you're trying to do. </p>\n\n<p><a href=\"http://support.microsoft.com/kb/226473\" rel=\"noreferrer\"><a href=\"http://support.microsoft.com/kb/226473\" rel=\"noreferrer\">http://support.microsoft.com/kb/226473</a></a></p>\n\n<p>The short version is you want to use the InternetOpen, InternetSetOption API's to update the proxy settings. </p>\n"
},
{
"answer_id": 209072,
"author": "JSBձոգչ",
"author_id": 8078,
"author_profile": "https://Stackoverflow.com/users/8078",
"pm_score": 6,
"selected": true,
"text": "<p>This depends somewhat on your exact needs. If you are writing a C# app and simply want to set the default proxy settings that your app will use, use the class System.Net.GlobalProxySelection (<a href=\"http://msdn.microsoft.com/en-us/library/system.net.globalproxyselection.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.net.globalproxyselection.aspx</a>). You can also set the proxy for any particular connection with System.Net.WebProxy (<a href=\"http://msdn.microsoft.com/en-us/library/system.net.webproxy.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.net.webproxy.aspx</a>).</p>\n\n<p>If you actually want to update the proxy settings in the registry, I believe that you'll need to use P/Invoke to call the WinAPI function WinHttpSetDefaultProxyConfiguration (<a href=\"http://msdn.microsoft.com/en-us/library/aa384113.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa384113.aspx</a>).</p>\n"
},
{
"answer_id": 4493545,
"author": "chris",
"author_id": 528844,
"author_profile": "https://Stackoverflow.com/users/528844",
"pm_score": 4,
"selected": false,
"text": "<p>from: <a href=\"http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/19517edf-8348-438a-a3da-5fbe7a46b61a\">http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/19517edf-8348-438a-a3da-5fbe7a46b61a</a></p>\n\n<p>Add these lines at the beginning of your code:</p>\n\n<p>using System.Runtime.InteropServices;\nusing Microsoft.Win32;</p>\n\n<pre><code> [DllImport(\"wininet.dll\")]\n public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);\n public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;\n public const int INTERNET_OPTION_REFRESH = 37;\n bool settingsReturn, refreshReturn;\n</code></pre>\n\n<p>And imply the code:</p>\n\n<pre><code> RegKey.SetValue(\"ProxyServer\", YOURPROXY);\n RegKey.SetValue(\"ProxyEnable\", 1);\n\n // These lines implement the Interface in the beginning of program \n // They cause the OS to refresh the settings, causing IP to realy update\n settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);\n refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);\n</code></pre>\n"
},
{
"answer_id": 8724165,
"author": "Dave",
"author_id": 150094,
"author_profile": "https://Stackoverflow.com/users/150094",
"pm_score": -1,
"selected": false,
"text": "<p>Quick Code example (from msdn):</p>\n\n<pre><code>WebProxy proxyObject = new WebProxy(\"http://proxyserver:80/\",true);\nWebRequest req = WebRequest.Create(\"http://www.contoso.com\");\nreq.Proxy = proxyObject;\n</code></pre>\n"
},
{
"answer_id": 13008235,
"author": "Naim Raja Díaz",
"author_id": 1764875,
"author_profile": "https://Stackoverflow.com/users/1764875",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this useful method existing since FW 2.0:\n(i've just discovered and i'm another man now...)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.webrequest.getsystemwebproxy.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.net.webrequest.getsystemwebproxy.aspx</a></p>\n"
},
{
"answer_id": 26273084,
"author": "131",
"author_id": 146457,
"author_profile": "https://Stackoverflow.com/users/146457",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote a 10 lines program to do that, feel free to try <a href=\"https://github.com/131/proxytoggle\" rel=\"nofollow noreferrer\">https://github.com/131/proxytoggle</a></p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Runtime.InteropServices;\nusing Microsoft.Win32;\n\nnamespace ProxyToggle\n{\n\n class Program\n {\n\n [DllImport("wininet.dll")]\n public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);\n public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;\n public const int INTERNET_OPTION_REFRESH = 37;\n\n\n static void setProxy(string proxyhost, bool proxyEnabled)\n {\n const string userRoot = "HKEY_CURRENT_USER";\n const string subkey = "Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Internet Settings";\n const string keyName = userRoot + "\\\\" + subkey;\n\n if(proxyhost.Length != 0)\n Registry.SetValue(keyName, "ProxyServer", proxyhost);\n Registry.SetValue(keyName, "ProxyEnable", proxyEnabled ? "1" : "0", RegistryValueKind.DWord);\n\n // These lines implement the Interface in the beginning of program \n // They cause the OS to refresh the settings, causing IP to realy update\n InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);\n InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);\n }\n\n static void Main(string[] args)\n {\n if (args.Length == 0)\n {\n setProxy("", false);\n return;\n }\n\n setProxy(args[0], true);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17623/"
] |
I'm writing an winforms app that needs to set internet explorer's proxy settings and then open a new browser window. At the moment, I'm applying the proxy settings by going into the registry:
```
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", "127.0.0.1:8080");
```
Is going into the registry the *best* way to do this, or is there a more recommended approach? I'd like to avoid registry changes if there's an alternative solution.
|
This depends somewhat on your exact needs. If you are writing a C# app and simply want to set the default proxy settings that your app will use, use the class System.Net.GlobalProxySelection (<http://msdn.microsoft.com/en-us/library/system.net.globalproxyselection.aspx>). You can also set the proxy for any particular connection with System.Net.WebProxy (<http://msdn.microsoft.com/en-us/library/system.net.webproxy.aspx>).
If you actually want to update the proxy settings in the registry, I believe that you'll need to use P/Invoke to call the WinAPI function WinHttpSetDefaultProxyConfiguration (<http://msdn.microsoft.com/en-us/library/aa384113.aspx>).
|
197,747 |
<p>I want to create a new row in my database on a table that has a couple of foreign key relationships and I haven't been able to get a handle on what order and what calls need to be made. This is what I have so far:</p>
<pre><code>db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.CustomerReference.Attach( ( from c in db.Customer where c.Id == custId select c ).First() );
db.SaveChanges();
</code></pre>
<p>The code is failing on the second line there, saying: </p>
<blockquote>
<p>Attach is not a valid operation when
the source object associated with this
related end is in an added, deleted,
or detached state. Objects loaded
using the NoTracking merge option are
always detached.</p>
</blockquote>
<p>Any ideas?</p>
|
[
{
"answer_id": 197842,
"author": "Jared",
"author_id": 24841,
"author_profile": "https://Stackoverflow.com/users/24841",
"pm_score": 4,
"selected": true,
"text": "<p><em>(Thanks John for the grammar fixes)</em></p>\n\n<p>So I figured it out. This is what you have to do:</p>\n\n<pre><code>db.Models.Order order = DB.Models.Order.CreateOrder( apple );\norder.Customer = (from c in db.Customer where c.Id == custId select c).First();\ndb.SaveChanges();\n</code></pre>\n\n<p>I hope that helps people.</p>\n"
},
{
"answer_id": 368867,
"author": "kirkmcpherson",
"author_id": 46400,
"author_profile": "https://Stackoverflow.com/users/46400",
"pm_score": 3,
"selected": false,
"text": "<p>Why not use entity references? Your method will cause an extra <code>SELECT</code> statement.</p>\n\n<p>A much nicer way is to use the <code>CustomerReference</code> class and an <code>EntityKey</code>.</p>\n\n<pre><code>order.CustomerReference = new System.Data.Objects.DataClasses.EntityReference<Customers>();\norder.CustomerReference.EntityKey = new EntityKey(\"ModelsEntities.Customers\", \"Id\", custId);\n</code></pre>\n"
},
{
"answer_id": 992906,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For update here is some sample code: </p>\n\n<pre><code>using (var ctx = new DataModelEntities())\n{\n\n var result = (from p in ctx.UserRole.Where(o => o.UserRoleId == userRole.UserRoleId)\n select p).First();\n\n result.RolesReference.EntityKey = new EntityKey(\"DataModelEntities.Roles\",\n \"RoleId\", userRole.RoleId);\n\n result.UserRoleDescription = userRole.UserRoleDescription; \n ctx.SaveChanges();\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24841/"
] |
I want to create a new row in my database on a table that has a couple of foreign key relationships and I haven't been able to get a handle on what order and what calls need to be made. This is what I have so far:
```
db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.CustomerReference.Attach( ( from c in db.Customer where c.Id == custId select c ).First() );
db.SaveChanges();
```
The code is failing on the second line there, saying:
>
> Attach is not a valid operation when
> the source object associated with this
> related end is in an added, deleted,
> or detached state. Objects loaded
> using the NoTracking merge option are
> always detached.
>
>
>
Any ideas?
|
*(Thanks John for the grammar fixes)*
So I figured it out. This is what you have to do:
```
db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.Customer = (from c in db.Customer where c.Id == custId select c).First();
db.SaveChanges();
```
I hope that helps people.
|
197,748 |
<p>Anyone know a simple method to swap the background color of a webpage using JavaScript?</p>
|
[
{
"answer_id": 197761,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "<p>Modify the JavaScript property <code>document.body.style.background</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>function changeBackground(color) {\n document.body.style.background = color;\n}\n\nwindow.addEventListener(\"load\",function() { changeBackground('red') });\n</code></pre>\n\n<p>Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.</p>\n"
},
{
"answer_id": 197763,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 2,
"selected": false,
"text": "<p>I wouldn't really class this as \"AJAX\". Anyway, something like following should do the trick: </p>\n\n<pre><code>document.body.style.backgroundColor = 'pink';\n</code></pre>\n"
},
{
"answer_id": 197764,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 6,
"selected": false,
"text": "<p>You don't need AJAX for this, just some plain java script setting the background-color property of the body element, like this:</p>\n\n<pre><code>document.body.style.backgroundColor = \"#AA0000\";\n</code></pre>\n\n<p>If you want to do it as if it was initiated by the server, you would have to poll the server and then change the color accordingly.</p>\n"
},
{
"answer_id": 197771,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 4,
"selected": false,
"text": "<p>AJAX is getting data from the server using Javascript and XML in an asynchronous fashion. Unless you want to download the colour code from the server, that's not what you're really aiming for!</p>\n\n<p>But otherwise you can set the CSS background with Javascript. If you're using a framework like jQuery, it'll be something like this:</p>\n\n<pre><code>$('body').css('background', '#ccc');\n</code></pre>\n\n<p>Otherwise, this should work:</p>\n\n<pre><code>document.body.style.background = \"#ccc\";\n</code></pre>\n"
},
{
"answer_id": 197833,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 2,
"selected": false,
"text": "<p>I would prefer to see the use of a css class here. It avoids having hard to read colors / hex codes in javascript.</p>\n\n<pre><code>document.body.className = className;\n</code></pre>\n"
},
{
"answer_id": 197899,
"author": "Martin Kool",
"author_id": 216896,
"author_profile": "https://Stackoverflow.com/users/216896",
"pm_score": 4,
"selected": false,
"text": "<p>I agree with the previous poster that changing the color by <code>className</code> is a prettier approach. My argument however is that a <code>className</code> can be regarded as a definition of \"why you want the background to be this or that color.\" </p>\n\n<p>For instance, making it red is not just because you want it red, but because you'd want to inform users of an error. As such, setting the className <code>AnErrorHasOccured</code> on the body would be my preferred implementation.</p>\n\n<p>In css</p>\n\n<pre><code>body.AnErrorHasOccured\n{\n background: #f00;\n}\n</code></pre>\n\n<p>In JavaScript:</p>\n\n<pre><code>document.body.className = \"AnErrorHasOccured\";\n</code></pre>\n\n<p>This leaves you the options of styling more elements according to this <code>className</code>. And as such, by setting a <code>className</code> you kind of give the page a certain state.</p>\n"
},
{
"answer_id": 4866010,
"author": "james.garriss",
"author_id": 584674,
"author_profile": "https://Stackoverflow.com/users/584674",
"pm_score": 2,
"selected": false,
"text": "<p>Add this script element to your body element, changing the color as desired:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body>\r\n <p>Hello, World!</p>\r\n <script type=\"text/javascript\">\r\n document.body.style.backgroundColor = \"#ff0000\"; // red\r\n </script>\r\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 13194318,
"author": "defau1t",
"author_id": 724764,
"author_profile": "https://Stackoverflow.com/users/724764",
"pm_score": 2,
"selected": false,
"text": "<p>You can change background of a page by simply using:</p>\n\n<pre><code>document.body.style.background = #000000; //I used black as color code\n</code></pre>\n\n<p>However the below script will change the background of the page after every 3 seconds using setTimeout() function:</p>\n\n<pre><code>$(function() {\n var colors = [\"#0099cc\",\"#c0c0c0\",\"#587b2e\",\"#990000\",\"#000000\",\"#1C8200\",\"#987baa\",\"#981890\",\"#AA8971\",\"#1987FC\",\"#99081E\"];\n\n setInterval(function() { \n var bodybgarrayno = Math.floor(Math.random() * colors.length);\n var selectedcolor = colors[bodybgarrayno];\n $(\"body\").css(\"background\",selectedcolor);\n }, 3000);\n })\n</code></pre>\n\n<p><a href=\"http://codeforbrowser.com/blog/changing-background-color-using-javascript-and-jquery/\" rel=\"nofollow\"><strong>READ MORE</strong></a><br /><br /><a href=\"http://jsfiddle.net/refhat/gJWFR/1/\" rel=\"nofollow\"><strong>DEMO</strong></a></p>\n"
},
{
"answer_id": 19145226,
"author": "gaby de wilde",
"author_id": 2117400,
"author_profile": "https://Stackoverflow.com/users/2117400",
"pm_score": 0,
"selected": false,
"text": "<p>But you would want to configure the body color before the <code><body></code> element exists. That way it has the right color from the get go.</p>\n\n<pre><code><script>\n var myColor = \"#AAAAAA\";\n document.write('\\\n <style>\\\n body{\\\n background-color: '+myColor+';\\\n }\\\n </style>\\\n ');\n</script>\n</code></pre>\n\n<p>This you can put in the <code><head></code> of the document or in your js file.</p>\n\n<p>Here is a nice color to play with.</p>\n\n<pre><code>var myColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);\n</code></pre>\n"
},
{
"answer_id": 28083129,
"author": "joel hills",
"author_id": 4481398,
"author_profile": "https://Stackoverflow.com/users/4481398",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest the following code:</p>\n\n<pre><code><div id=\"example\" onClick=\"colorize()\">Click on this text to change the\nbackground color</div>\n<script type='text/javascript'>\nfunction colorize() {\nvar element = document.getElementById(\"example\");\nelement.style.backgroundColor='#800';\nelement.style.color='white';\nelement.style.textAlign='center';\n}\n</script>\n</code></pre>\n"
},
{
"answer_id": 28734873,
"author": "Vignesh Subramanian",
"author_id": 848841,
"author_profile": "https://Stackoverflow.com/users/848841",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it in following ways\n<strong>STEP 1</strong> </p>\n\n<pre><code> var imageUrl= \"URL OF THE IMAGE HERE\";\n var BackgroundColor=\"RED\"; // what ever color you want\n</code></pre>\n\n<p>For changing background of <strong>BODY</strong></p>\n\n<pre><code>document.body.style.backgroundImage=imageUrl //changing bg image\ndocument.body.style.backgroundColor=BackgroundColor //changing bg color\n</code></pre>\n\n<p><strong>To change an element with ID</strong></p>\n\n<pre><code>document.getElementById(\"ElementId\").style.backgroundImage=imageUrl\ndocument.getElementById(\"ElementId\").style.backgroundColor=BackgroundColor \n</code></pre>\n\n<p><strong>for elements with same class</strong></p>\n\n<pre><code> var elements = document.getElementsByClassName(\"ClassName\")\n for (var i = 0; i < elements.length; i++) {\n elements[i].style.background=imageUrl;\n }\n</code></pre>\n"
},
{
"answer_id": 39315370,
"author": "Deniz.parlak",
"author_id": 6754044,
"author_profile": "https://Stackoverflow.com/users/6754044",
"pm_score": 2,
"selected": false,
"text": "<p>Css approach:</p>\n\n<p>If you want to see continuous colour, use this code:</p>\n\n<pre><code>body{\n background-color:black;\n animation: image 10s infinite alternate;\n animation:image 10s infinite alternate;\n animation:image 10s infinite alternate;\n}\n\n@keyframes image{\n 0%{\nbackground-color:blue;\n}\n25%/{\n background-color:red;\n}\n50%{\n background-color:green;\n}\n75%{\n\n background-color:pink;\n}\n100%{\n background-color:yellow;\n }\n } \n</code></pre>\n\n<p>If you want to see it faster or slower, change 10 second to 5 second etc.</p>\n"
},
{
"answer_id": 43015885,
"author": "Ritam Das",
"author_id": 5400367,
"author_profile": "https://Stackoverflow.com/users/5400367",
"pm_score": 2,
"selected": false,
"text": "<p>This will change the background color according to the choice of user selected from the drop-down menu:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function changeBG() {\r\n var selectedBGColor = document.getElementById(\"bgchoice\").value;\r\n document.body.style.backgroundColor = selectedBGColor;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><select id=\"bgchoice\" onchange=\"changeBG()\">\r\n <option></option>\r\n <option value=\"red\">Red</option>\r\n <option value=\"ivory\">Ivory</option>\r\n <option value=\"pink\">Pink</option>\r\n</select></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48926051,
"author": "Alex",
"author_id": 9226166,
"author_profile": "https://Stackoverflow.com/users/9226166",
"pm_score": 2,
"selected": false,
"text": "<p>if you wish to use a button or some other event, just use this in JS:</p>\n\n<pre><code>document.querySelector(\"button\").addEventListener(\"click\", function() {\ndocument.body.style.backgroundColor = \"red\";\n});\n</code></pre>\n"
},
{
"answer_id": 49526545,
"author": "jonathan klevin",
"author_id": 9466285,
"author_profile": "https://Stackoverflow.com/users/9466285",
"pm_score": 1,
"selected": false,
"text": "<p>You can change background of a page by simply using:</p>\n\n<pre><code>function changeBodyBg(color){\n document.body.style.background = color;\n}\n</code></pre>\n\n<p>Read more @ <a href=\"http://www.jquerypot.com/how-to-change-the-background-color-of-a-web-page-dynamically-in-javascript/\" rel=\"nofollow noreferrer\">Changing the Background Color</a></p>\n"
},
{
"answer_id": 53256265,
"author": "Divakar Rajesh",
"author_id": 8950361,
"author_profile": "https://Stackoverflow.com/users/8950361",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively, if you wish to specify the background color value in rgb notation then try</p>\n<pre><code>document.getElementById("yourid").style.backgroundColor = `rgb(${a}, ${b}, ${c})`;\n</code></pre>\n<p>where a,b,c are the color values</p>\n<p>Example:</p>\n<pre><code>document.getElementById("yourid").style.backgroundColor = 'rgb(224,224,224)';\n</code></pre>\n"
},
{
"answer_id": 60974198,
"author": "Arslan",
"author_id": 11942876,
"author_profile": "https://Stackoverflow.com/users/11942876",
"pm_score": 2,
"selected": false,
"text": "<pre><code><!DOCTYPE html>\n<html>\n<body>\n<select name=\"\" id=\"select\" onClick=\"hello();\">\n <option>Select</option>\n <option style=\"background-color: #CD5C5C;\">#CD5C5C</option>\n <option style=\"background-color: #F08080;\">#F08080</option>\n <option style=\"background-color: #FA8072;\">#FA8072</option>\n <option style=\"background-color: #E9967A;\">#E9967A</option>\n <option style=\"background-color: #FFA07A;\">#FFA07A</option>\n</select>\n<script>\nfunction hello(){\nlet d = document.getElementById(\"select\");\nlet text = d.options[d.selectedIndex].value;\ndocument.body.style.backgroundColor=text;\n}\n</script>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 63435423,
"author": "Satish Chandra Gupta",
"author_id": 9445290,
"author_profile": "https://Stackoverflow.com/users/9445290",
"pm_score": 2,
"selected": false,
"text": "<h1>Here are 2 ways to Change Background Color Using Javascript</h1>\n<ol>\n<li><p>To change background color with javascript you can apply\n<strong><code>style.background</code></strong> or <strong><code>style.backgroundColor</code></strong> on the element you want to change background for.</p>\n<p>The below example changes the background color of the body when you\nclick an element using <code>style.background</code> property.</p>\n</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function pink(){ document.body.style.background = \"pink\"; }\nfunction sky(){ document.body.style.background = \"skyblue\"; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p onclick=\"pink()\" style=\"padding:10px;background:pink\">Pink</p>\n<p onclick=\"sky()\" style=\"padding:10px;background:skyblue\">Sky</p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<ol start=\"2\">\n<li><p>Another approach could be by adding a CSS class using\njavascript\nthat gives a background to the element it is attached.</p>\n<p>You can see more ways to add class using javascript but here you can\nsimply use <code>classList.add()</code> property.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> function addClass(yourClass){\n document.body.classList.remove(\"sky\", \"pink\");\n document.body.classList.add(yourClass);\n }</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code> .pink {\n background: pink;\n }\n\n .sky {\n background: skyblue;\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <p onclick=\"addClass('pink')\" style=\"padding:10px;background:pink\">Pink</p>\n <p onclick=\"addClass('sky')\" style=\"padding:10px;background:skyblue\">Sky</p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n</li>\n</ol>\n"
},
{
"answer_id": 66174009,
"author": "Kia Boluki",
"author_id": 2719481,
"author_profile": "https://Stackoverflow.com/users/2719481",
"pm_score": -1,
"selected": false,
"text": "<p>This code makes random color for background every second.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>setInterval(changeColor,1000);\nfunction changeColor(){\n let r = Math.random() * 255 ;\n let g = Math.random() * 255 ;\n let b = Math.random() * 255 ;\n \n document.body.style.backgroundColor = `rgb( ${r}, ${g}, ${b} )`;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I hope helps someone.❤</p>\n"
},
{
"answer_id": 67374178,
"author": "Moazzam S",
"author_id": 11967419,
"author_profile": "https://Stackoverflow.com/users/11967419",
"pm_score": -1,
"selected": false,
"text": "<pre><code> <p id="p1">Hello, Moazzam!</p>\n <p >Hello, Moazzam!</p>\n <p >Hello, Moazzam!</p>\n <script type="text/javascript">\n document.getElementById("p1").style.color= "#ff0000"; // red\n </script>\n</code></pre>\n"
},
{
"answer_id": 69371706,
"author": "salik saleem",
"author_id": 9542718,
"author_profile": "https://Stackoverflow.com/users/9542718",
"pm_score": 2,
"selected": false,
"text": "<p>so you can done very easily by just calling a function like</p>\n<pre><code> function changeBg()\n {\n document.body.style.color.backgroundColor="#ffffff";\n\n }\n</code></pre>\n"
},
{
"answer_id": 72726955,
"author": "Mouzam Ali",
"author_id": 7188711,
"author_profile": "https://Stackoverflow.com/users/7188711",
"pm_score": 0,
"selected": false,
"text": "<p>It can be achieved using</p>\n<pre><code>document.body.style.color.backgroundColor="#000000";\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
Anyone know a simple method to swap the background color of a webpage using JavaScript?
|
Modify the JavaScript property `document.body.style.background`.
For example:
```
function changeBackground(color) {
document.body.style.background = color;
}
window.addEventListener("load",function() { changeBackground('red') });
```
Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.
|
197,753 |
<p>I have 2 classes with a LINQ association between them i.e.:</p>
<pre><code>Table1: Table2:
ID ID
Name Description
ForiegnID
</code></pre>
<p>The association here is between <strong>Table1.ID -> Table2.ForiegnID</strong></p>
<p>I need to be able to change the value of Table2.ForiegnID, however I can't and think it is because of the association (as when I remove it, it works).</p>
<p>Therefore, does anyone know how I can change the value of the associated field Table2.ForiegnID?</p>
|
[
{
"answer_id": 197814,
"author": "Zote",
"author_id": 20683,
"author_profile": "https://Stackoverflow.com/users/20683",
"pm_score": 0,
"selected": false,
"text": "<p>You wanna to associate with another record in table1 or change table1.id?\nif it's option 1, you need to remove that association and set a new one.\nIf option 2, check you db and see if update cascade yes enabled for this fk and than get record and change value of id.</p>\n"
},
{
"answer_id": 197826,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "<p>Check out the designer.cs file. This is the key's property</p>\n\n<pre><code>[Column(Storage=\"_ParentKey\", DbType=\"Int\")]\npublic System.Nullable<int> ParentKey\n{\n get\n {\n return this._ParentKey;\n }\n set\n {\n if ((this._ParentKey != value))\n {\n //This code is added by the association\n if (this._Parent.HasLoadedOrAssignedValue)\n {\n throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\n }\n //This code is present regardless of association\n this.OnParentKeyChanging(value);\n this.SendPropertyChanging();\n this._ParentKey = value;\n this.SendPropertyChanged(\"ParentKey\");\n this.OnServiceAddrIDChanged();\n }\n }\n}\n</code></pre>\n\n<p>And this is the associations property.</p>\n\n<pre><code>[Association(Name=\"Parent_Child\", Storage=\"_Parent\", ThisKey=\"ParentKey\", IsForeignKey=true, DeleteRule=\"CASCADE\")]\npublic Parent Parent\n{\n get\n {\n return this._Parent.Entity;\n }\n set\n {\n Parent previousValue = this._Parent.Entity;\n if (((previousValue != value) \n || (this._Parent.HasLoadedOrAssignedValue == false)))\n {\n this.SendPropertyChanging();\n if ((previousValue != null))\n {\n this._Parent.Entity = null;\n previousValue.Exemptions.Remove(this);\n }\n this._Parent.Entity = value;\n if ((value != null))\n {\n value.Exemptions.Add(this);\n this._ParentKey = value.ParentKey;\n }\n else\n {\n this._ParentKey = default(Nullable<int>);\n }\n this.SendPropertyChanged(\"Parent\");\n }\n }\n}\n</code></pre>\n\n<p>It's best to assign changes through the association instead of the key. That way, you don't have to worry about whether the parent is loaded.</p>\n"
},
{
"answer_id": 839674,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Table1: Table2:\nID ID\nName Description\n ForeignID\n</code></pre>\n\n<p>With this :</p>\n\n<p>Table2.ForeignID = 2</p>\n\n<p>you receive an error..........</p>\n\n<p>Example :</p>\n\n<p>You can change ForeignID field in Table 2 whit this :</p>\n\n<pre><code> Table2 table = dataContext.Table2.single(d => d.ID == Id)\n\n table.Table1 = dataContext.Table1.single(d => d.ID == newId);\n</code></pre>\n\n<p>Where the variable <code>newId</code> is the id of the record in Table 2 that would you like associate whit the record in Table 1</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989/"
] |
I have 2 classes with a LINQ association between them i.e.:
```
Table1: Table2:
ID ID
Name Description
ForiegnID
```
The association here is between **Table1.ID -> Table2.ForiegnID**
I need to be able to change the value of Table2.ForiegnID, however I can't and think it is because of the association (as when I remove it, it works).
Therefore, does anyone know how I can change the value of the associated field Table2.ForiegnID?
|
Check out the designer.cs file. This is the key's property
```
[Column(Storage="_ParentKey", DbType="Int")]
public System.Nullable<int> ParentKey
{
get
{
return this._ParentKey;
}
set
{
if ((this._ParentKey != value))
{
//This code is added by the association
if (this._Parent.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
//This code is present regardless of association
this.OnParentKeyChanging(value);
this.SendPropertyChanging();
this._ParentKey = value;
this.SendPropertyChanged("ParentKey");
this.OnServiceAddrIDChanged();
}
}
}
```
And this is the associations property.
```
[Association(Name="Parent_Child", Storage="_Parent", ThisKey="ParentKey", IsForeignKey=true, DeleteRule="CASCADE")]
public Parent Parent
{
get
{
return this._Parent.Entity;
}
set
{
Parent previousValue = this._Parent.Entity;
if (((previousValue != value)
|| (this._Parent.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Parent.Entity = null;
previousValue.Exemptions.Remove(this);
}
this._Parent.Entity = value;
if ((value != null))
{
value.Exemptions.Add(this);
this._ParentKey = value.ParentKey;
}
else
{
this._ParentKey = default(Nullable<int>);
}
this.SendPropertyChanged("Parent");
}
}
}
```
It's best to assign changes through the association instead of the key. That way, you don't have to worry about whether the parent is loaded.
|
197,757 |
<p>I was trying to understand something with pointers, so I wrote this code:</p>
<pre><code>#include <stdio.h>
int main(void)
{
char s[] = "asd";
char **p = &s;
printf("The value of s is: %p\n", s);
printf("The direction of s is: %p\n", &s);
printf("The value of p is: %p\n", p);
printf("The direction of p is: %p\n", &p);
printf("The direction of s[0] is: %p\n", &s[0]);
printf("The direction of s[1] is: %p\n", &s[1]);
printf("The direction of s[2] is: %p\n", &s[2]);
return 0;
}
</code></pre>
<p>When compiling it with gcc I get these warnings:</p>
<pre><code>$ gcc main.c -o main-bin -ansi -pedantic -Wall -lm
main.c: In function ‘main’:
main.c:6: warning: initialization from incompatible pointer type
main.c:9: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char (*)[4]’
main.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char **’
main.c:12: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char ***’
</code></pre>
<p>(The flags for gcc are because I must be C89)</p>
<p>Why incompatible types of pointer? Isn't the name of an array a pointer to it's first element? So if s is a pointer to 'a', <code>&s</code> must be a <code>char **</code>, no?
And why do I get the other warnings? Do I have to cast the pointers with (<code>void *</code>) in order to print them? </p>
<p>And when running I get something like this:</p>
<pre><code>$ ./main-bin
The value of s is: 0xbfb7c860
The direction of s is: 0xbfb7c860
The value of p is: 0xbfb7c860
The direction of p is: 0xbfb7c85c
The direction of s[0] is: 0xbfb7c860
The direction of s[1] is: 0xbfb7c861
The direction of s[2] is: 0xbfb7c862
</code></pre>
<p>How can the value of s and it's direction (and of course the value of <code>p</code>) be the same?</p>
|
[
{
"answer_id": 197768,
"author": "selwyn",
"author_id": 16314,
"author_profile": "https://Stackoverflow.com/users/16314",
"pm_score": 0,
"selected": false,
"text": "<p>You have used:</p>\n\n<pre><code>char s[] = \"asd\";\n</code></pre>\n\n<p>Here s actually points to the bytes \"asd\". The address of s, would also point to this location.</p>\n\n<p>If you used:</p>\n\n<pre><code>char *s = \"asd\";\n</code></pre>\n\n<p>the value of s and &s would be different, as s would actually be a pointer to the bytes \"asd\".</p>\n\n<p>You used:</p>\n\n<pre><code>char s[] = \"asd\";\nchar **p = &s;\n</code></pre>\n\n<p>Here s points to the bytes \"asd\". p is a pointer to a pointer to characters, and has been set to a the address of characters. In other words you have too many indirections in p. If you used char *s = \"asd\", you could use this additional indirection.</p>\n"
},
{
"answer_id": 197780,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 5,
"selected": false,
"text": "<p>Yes, your compiler is expecting void *. Just cast them to void *.</p>\n\n<pre><code>/* for instance... */\nprintf(\"The value of s is: %p\\n\", (void *) s);\nprintf(\"The direction of s is: %p\\n\", (void *) &s);\n</code></pre>\n"
},
{
"answer_id": 197791,
"author": "Sergey Golovchenko",
"author_id": 26592,
"author_profile": "https://Stackoverflow.com/users/26592",
"pm_score": 1,
"selected": false,
"text": "<p>change line:</p>\n<pre><code>char s[] = "asd";\n</code></pre>\n<p>to:</p>\n<pre><code>char *s = "asd";\n</code></pre>\n<p>and things will get more clear</p>\n"
},
{
"answer_id": 197800,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 2,
"selected": false,
"text": "<p>If you pass the name of an array as an argument to a function, it is treated as if you had passed the address of the array. So &s and s are identical arguments. See K&R 5.3. &s[0] is the same as &s, since it takes the address of the first element of the array, which is the same as taking the address of the array itself.</p>\n\n<p>For all the others, although all pointers are essentially memory locations they are still typed, and the compiler will warn about assigning one type of pointer to another. </p>\n\n<ul>\n<li><code>void* p;</code> says p is a memory address, but I don't know what's in the memory</li>\n<li><code>char* s;</code> says s is a memory address, and the first byte contains a character</li>\n<li><code>char** ps;</code> says ps is a memory address, and the four bytes there (for a 32-bit system) contain a pointer of type char*.</li>\n</ul>\n\n<p>cf <a href=\"http://www.oberon2005.ru/paper/kr_c.pdf\" rel=\"nofollow noreferrer\">http://www.oberon2005.ru/paper/kr_c.pdf</a> (e-book version of K&R)</p>\n"
},
{
"answer_id": 197801,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 1,
"selected": false,
"text": "<p>You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence <code>s == &s</code>. It's just a quirk of the language.</p>\n"
},
{
"answer_id": 197824,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 6,
"selected": true,
"text": "<p>\"s\" is not a \"char*\", it's a \"char[4]\". And so, \"&s\" is not a \"char**\", but actually \"a pointer to an array of 4 characater\". Your compiler may treat \"&s\" as if you had written \"&s[0]\", which is roughly the same thing, but is a \"char*\".</p>\n\n<p>When you write \"char** p = &s;\" you are trying to say \"I want p to be set to the address of the thing which currently points to \"asd\". But currently there is nothing which <em>points</em> to \"asd\". There is just an array which <em>holds</em> \"asd\";</p>\n\n<pre><code>char s[] = \"asd\";\nchar *p = &s[0]; // alternately you could use the shorthand char*p = s;\nchar **pp = &p;\n</code></pre>\n"
},
{
"answer_id": 198323,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 1,
"selected": false,
"text": "<p>Normally, it's considered poor style to unnecessarily cast pointers to (void*). Here, however, you need the casts to (void*) on the printf arguments because printf is variadic. The prototype doesn't tell the compiler what type to convert the pointers to at the call site. </p>\n"
},
{
"answer_id": 15423321,
"author": "4pie0",
"author_id": 1141471,
"author_profile": "https://Stackoverflow.com/users/1141471",
"pm_score": 2,
"selected": false,
"text": "<p>It's not a pointer to character <code>char*</code> but a pointer to array of 4 characters: <code>char* [4]</code>. With g++ it doesn't compile:</p>\n\n<blockquote>\n <p>main.cpp: In function ‘int main(int, char**)’: main.cpp:126: error:\n cannot convert ‘char (*)[4]’ to ‘char**’ in initialization</p>\n</blockquote>\n\n<p>Moreover, the linux man pages <a href=\"http://linux.die.net/man/3/printf\" rel=\"nofollow\">says</a>:</p>\n\n<blockquote>\n <p>p</p>\n \n <p>The void * pointer argument is printed in hexadecimal (as if by %#x or\n %#lx).\n It shoud be pointer to void.</p>\n</blockquote>\n\n<p>You can change your code to:</p>\n\n<pre><code>char* s = \"asd\";\nchar** p = &s;\n\nprintf(\"The value of s is: %p\\n\", s);\nprintf(\"The address of s is: %p\\n\", &s);\n\nprintf(\"The value of p is: %p\\n\", p);\nprintf(\"The address of p is: %p\\n\", &p);\n\nprintf(\"The address of s[0] is: %p\\n\", &s[0]);\nprintf(\"The address of s[1] is: %p\\n\", &s[1]);\nprintf(\"The address of s[2] is: %p\\n\", &s[2]);\n</code></pre>\n\n<p>result:</p>\n\n<p>The value of s is: 0x403f00 </p>\n\n<p>The address of s is: 0x7fff2df9d588</p>\n\n<p>The value of p is: 0x7fff2df9d588 </p>\n\n<p>The address of p is: 0x7fff2df9d580 </p>\n\n<p>The address of s[0] is: 0x403f00 </p>\n\n<p>The address of s[1] is: 0x403f01 </p>\n\n<p>The address of s[2] is: 0x403f02</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27267/"
] |
I was trying to understand something with pointers, so I wrote this code:
```
#include <stdio.h>
int main(void)
{
char s[] = "asd";
char **p = &s;
printf("The value of s is: %p\n", s);
printf("The direction of s is: %p\n", &s);
printf("The value of p is: %p\n", p);
printf("The direction of p is: %p\n", &p);
printf("The direction of s[0] is: %p\n", &s[0]);
printf("The direction of s[1] is: %p\n", &s[1]);
printf("The direction of s[2] is: %p\n", &s[2]);
return 0;
}
```
When compiling it with gcc I get these warnings:
```
$ gcc main.c -o main-bin -ansi -pedantic -Wall -lm
main.c: In function ‘main’:
main.c:6: warning: initialization from incompatible pointer type
main.c:9: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char (*)[4]’
main.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char **’
main.c:12: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char ***’
```
(The flags for gcc are because I must be C89)
Why incompatible types of pointer? Isn't the name of an array a pointer to it's first element? So if s is a pointer to 'a', `&s` must be a `char **`, no?
And why do I get the other warnings? Do I have to cast the pointers with (`void *`) in order to print them?
And when running I get something like this:
```
$ ./main-bin
The value of s is: 0xbfb7c860
The direction of s is: 0xbfb7c860
The value of p is: 0xbfb7c860
The direction of p is: 0xbfb7c85c
The direction of s[0] is: 0xbfb7c860
The direction of s[1] is: 0xbfb7c861
The direction of s[2] is: 0xbfb7c862
```
How can the value of s and it's direction (and of course the value of `p`) be the same?
|
"s" is not a "char\*", it's a "char[4]". And so, "&s" is not a "char\*\*", but actually "a pointer to an array of 4 characater". Your compiler may treat "&s" as if you had written "&s[0]", which is roughly the same thing, but is a "char\*".
When you write "char\*\* p = &s" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which *points* to "asd". There is just an array which *holds* "asd";
```
char s[] = "asd";
char *p = &s[0]; // alternately you could use the shorthand char*p = s;
char **pp = &p;
```
|
197,758 |
<p>I have a bunch of XML that has lines that look like this</p>
<pre><code><_char font_name="/ITC Stone Serif Std Bold" italic="true" />
</code></pre>
<p>but sometimes look like this</p>
<pre><code><_char font_size="88175" italic="true" font_name="/ITC Stone Serif Std Bold" />
</code></pre>
<p>Here's what I need to do</p>
<ul>
<li>Replace <strong>italic="true"</strong> with <strong>italic="false</strong> for every line that contains <strong>ITC Stone Serif Std Bold</strong>, regardless of whether it comes before OR after the <strong>italic</strong> part.</li>
</ul>
<p>Can this be done with a single regex?</p>
<p>I'm not looking for a real-time solution. I just have a ton of XML files that have this "mistake" in them and I'm trying to do a global search-and-replace with PowerGrep which would require a single regex. If scripting's the only way to do it, then so be it.</p>
|
[
{
"answer_id": 197804,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 1,
"selected": false,
"text": "<p>Well, in general, using RE for XML parsing isn't a great idea. But if you really wanted, the easiest way would be to just do it in two lines:</p>\n\n<pre><code>if (/ITC Stone Serif Std Bold/) {\n s/italic=\"true\"/italic=\"false\"/g;\n}\n</code></pre>\n"
},
{
"answer_id": 197805,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "<p>Does the simple use of '|' operator satisfy you ?</p>\n\n<pre><code>name=\"/ITC Stone Sans Std Bold\"[^>]italic=\"(true)\"|italic=\"(true)\"[^>]font_name=\"/ITC Stone Serif Std Bold\"\n</code></pre>\n\n<p>That should detect any line with the attribute name before of after attribute italic with value true.</p>\n"
},
{
"answer_id": 197813,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>In Perl - untested:</p>\n\n<pre><code>while (<>)\n{\n s/italic=\"true\"/italic=\"false\"/ if m%font_name=\"/ITC Stone Sans Std Bold\" italic=\"true\"|italic=\"true\" font_name=\"/ITC Stone Serif Std Bold\"%;\n print;\n}\n</code></pre>\n\n<p>Very simple minded - might need a global qualifier, might need a more complex substitute if other parts of the same line could contain italic options.</p>\n\n<p>Also - a thought - should you take this opportunity to make the notation uniform, so always put italic in front of (or behind) the font name?</p>\n"
},
{
"answer_id": 198103,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Pattern: /(<_char(?=(?:\\s+\\w+=\"[^\"]*\")*?\\s+font_name=\"[^\"]*?ITC Stone Serif Std Bold[^\"]*\")(?:\\s+\\w+=\"[^\"]*\")*?\\s+italic=\")true(?=\")/\nReplacement: '$1false'\n</code></pre>\n"
},
{
"answer_id": 207422,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "<h3>Perl 5.10</h3>\n<p>Using new features of Perl 5.10.</p>\n<pre><code>s(\n <_char \\s* [^>]*? \\K (?: (?&font) \\s+ (?&italic) | (?&italic) \\s+ (?&font) )\n (?(DEFINE)\n (?<font>font_name="/ITC[ ]Stone[ ]Serif[ ]Std[ ]Bold")\n (?<italic>italic="true")\n )\n){\n $+{font} . 'italic="false"'\n}xge\n</code></pre>\n<p><em>Warning: not tested.</em></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
I have a bunch of XML that has lines that look like this
```
<_char font_name="/ITC Stone Serif Std Bold" italic="true" />
```
but sometimes look like this
```
<_char font_size="88175" italic="true" font_name="/ITC Stone Serif Std Bold" />
```
Here's what I need to do
* Replace **italic="true"** with **italic="false** for every line that contains **ITC Stone Serif Std Bold**, regardless of whether it comes before OR after the **italic** part.
Can this be done with a single regex?
I'm not looking for a real-time solution. I just have a ton of XML files that have this "mistake" in them and I'm trying to do a global search-and-replace with PowerGrep which would require a single regex. If scripting's the only way to do it, then so be it.
|
Does the simple use of '|' operator satisfy you ?
```
name="/ITC Stone Sans Std Bold"[^>]italic="(true)"|italic="(true)"[^>]font_name="/ITC Stone Serif Std Bold"
```
That should detect any line with the attribute name before of after attribute italic with value true.
|
197,759 |
<p>I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. </p>
<p>I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string:</p>
<p>"^LThis is an example ^Gstring with multiple ^Jcharacter encodings"</p>
<p>Where the different encoding starts and ends is marked using special escape chars:</p>
<ul>
<li>^L - Latin1</li>
<li>^E - Central Europe</li>
<li>^T - Turkish</li>
<li>^B - Baltic</li>
<li>^J - Japanese</li>
<li>^C - Cyrillic</li>
<li>^G - Greek</li>
</ul>
<p>And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host.</p>
<p>I hope someone can help me with how to get started on this.</p>
|
[
{
"answer_id": 197786,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 2,
"selected": false,
"text": "<p>I would write a codec that incrementally scanned the string and decoded the bytes as they came along. Essentially, you would have to separate strings into chunks with a consistent encoding and decode those and append them to the strings that followed them.</p>\n"
},
{
"answer_id": 197846,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 3,
"selected": true,
"text": "<p>There's no built-in functionality for decoding a string like this, since it is really its own custom codec. You simply need to split up the string on those control characters and decode it accordingly.</p>\n\n<p>Here's a (very slow) example of such a function that handles latin1 and shift-JIS:</p>\n\n<pre><code>latin1 = \"latin-1\"\njapanese = \"Shift-JIS\"\n\ncontrol_l = \"\\x0c\"\ncontrol_j = \"\\n\"\n\nencodingMap = {\n control_l: latin1,\n control_j: japanese}\n\ndef funkyDecode(s, initialCodec=latin1):\n output = u\"\"\n accum = \"\"\n currentCodec = initialCodec\n for ch in s:\n if ch in encodingMap:\n output += accum.decode(currentCodec)\n currentCodec = encodingMap[ch]\n accum = \"\"\n else:\n accum += ch\n output += accum.decode(currentCodec)\n return output\n</code></pre>\n\n<p>A faster version might use str.split, or regular expressions.</p>\n\n<p>(Also, as you can see in this example, \"^J\" is the control character for \"newline\", so your input data is going to have some interesting restrictions.)</p>\n"
},
{
"answer_id": 197854,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 1,
"selected": false,
"text": "<p>I don't suppose you have any way of convincing the person who hosts the other machine to switch to unicode?</p>\n\n<p>This is one of the reasons Unicode was invented, after all.</p>\n"
},
{
"answer_id": 197982,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "<p>You definitely have to split the string first into the substrings wih different encodings, and decode each one separately. Just for fun, the obligatory \"one-line\" version:</p>\n\n<pre><code>import re\n\nencs = {\n 'L': 'latin1',\n 'G': 'iso8859-7',\n ...\n}\n\ndecoded = ''.join(substr[2:].decode(encs[substr[1]])\n for substr in re.findall('\\^[%s][^^]*' % ''.join(encs.keys()), st))\n</code></pre>\n\n<p>(no error checking, and also you'll want to decide how to handle '^' characters in substrings)</p>\n"
},
{
"answer_id": 197990,
"author": "zellyn",
"author_id": 23582,
"author_profile": "https://Stackoverflow.com/users/23582",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a relatively simple example of how do it...</p>\n\n<pre><code># -*- coding: utf-8 -*-\nimport re\n\n# Test Data\nENCODING_RAW_DATA = (\n ('latin_1', 'L', u'Hello'), # Latin 1\n ('iso8859_2', 'E', u'dobrý večer'), # Central Europe\n ('iso8859_9', 'T', u'İyi akşamlar'), # Turkish\n ('iso8859_13', 'B', u'Į sveikatą!'), # Baltic\n ('shift_jis', 'J', u'今日は'), # Japanese\n ('iso8859_5', 'C', u'Здравствуйте'), # Cyrillic\n ('iso8859_7', 'G', u'Γειά σου'), # Greek\n)\n\nCODE_TO_ENCODING = dict([(chr(ord(code)-64), encoding) for encoding, code, text in ENCODING_RAW_DATA])\nEXPECTED_RESULT = u''.join([line[2] for line in ENCODING_RAW_DATA])\nENCODED_DATA = ''.join([chr(ord(code)-64) + text.encode(encoding) for encoding, code, text in ENCODING_RAW_DATA])\n\nFIND_RE = re.compile('[\\x00-\\x1A][^\\x00-\\x1A]*')\n\ndef decode_single(bytes):\n return bytes[1:].decode(CODE_TO_ENCODING[bytes[0]])\n\nresult = u''.join([decode_single(bytes) for bytes in FIND_RE.findall(ENCODED_DATA)])\n\nassert result==EXPECTED_RESULT, u\"Expected %s, but got %s\" % (EXPECTED_RESULT, result)\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27059/"
] |
I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me.
I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string:
"^LThis is an example ^Gstring with multiple ^Jcharacter encodings"
Where the different encoding starts and ends is marked using special escape chars:
* ^L - Latin1
* ^E - Central Europe
* ^T - Turkish
* ^B - Baltic
* ^J - Japanese
* ^C - Cyrillic
* ^G - Greek
And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host.
I hope someone can help me with how to get started on this.
|
There's no built-in functionality for decoding a string like this, since it is really its own custom codec. You simply need to split up the string on those control characters and decode it accordingly.
Here's a (very slow) example of such a function that handles latin1 and shift-JIS:
```
latin1 = "latin-1"
japanese = "Shift-JIS"
control_l = "\x0c"
control_j = "\n"
encodingMap = {
control_l: latin1,
control_j: japanese}
def funkyDecode(s, initialCodec=latin1):
output = u""
accum = ""
currentCodec = initialCodec
for ch in s:
if ch in encodingMap:
output += accum.decode(currentCodec)
currentCodec = encodingMap[ch]
accum = ""
else:
accum += ch
output += accum.decode(currentCodec)
return output
```
A faster version might use str.split, or regular expressions.
(Also, as you can see in this example, "^J" is the control character for "newline", so your input data is going to have some interesting restrictions.)
|
197,793 |
<p>I'm building my first flex app and am currently bussy splitting it up in multiple components to make it maintainable.
I have a screen which holds a list that is displayed and filled after a succesfull login attempt:</p>
<p>Part of the main app:</p>
<pre><code><mx:ViewStack id="vsAdmin" height="100%" width="100%">
<mx:TabNavigator id="adminTabs" width="100%" height="100%" historyManagementEnabled="false">
<myComp:compBeheerdersAdmin id="beheerdersViewstackA"/>
</mx:TabNavigator>
</mx:ViewStack>
</code></pre>
<p>In the component compBeheerdersAdmin there is a function requestBeheerdersList() that gets the data from the server and Binds it to the list through a handler.</p>
<p>After login the following code from the main app:</p>
<pre><code>mainViewstack.selectedChild = vsAdmin;
//beheerdersViewstackA.createComponentsFromDescriptors();
beheerdersViewstackA.requestBeheerdersList();
</code></pre>
<p>The function requestBeheerdersList() does nothing (is not reached, i put a alert as first statement in the function but that is not displayed) when i login after a fresh load of the swf, but when i logout and login again, then the function is reached and the alert is displayed and the list is filled with the data from the server.
Any ideas?</p>
|
[
{
"answer_id": 198034,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": 1,
"selected": false,
"text": "<p>I would make sure the component exists that you are calling before calling the next function. This could be done by forcing creationPolicy=all as you figured out. You could also add an event listener for the CreationComplete to call the function you want:</p>\n\n<pre><code>private function doThisFirst():void{\n mainViewstack.selectedChild = vsAdmin;\n vsAdmin.addEventListener(FlexEvent.CREATION_COMPLETE,doThis);\n}\n\n\nprivate function doThis():void{\n beheerdersViewstackA.requestBeheerdersList();\n}\n</code></pre>\n\n<p>This may not be exactly correct but I tried to recreate to your specific example. If you are familiar with viewstack creation of its children and eventlisteners you should be able to fit this to your specific need.</p>\n"
},
{
"answer_id": 233168,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Alternatively, you can have creationComplete define in your mxml</p>\n\n<pre><code><mx:Canvas ... creationComplete=\"onCreationComplete()\">\n\n<mx:Script>\n <![CDATA[\n private function onCreationComplete():void {\n requestBeheerdersList()\n }\n ]]>\n</mx:Script>\n</code></pre>\n\n<p>or possibly </p>\n\n<pre><code><mx:Canvas ... creationComplete=\"requestBeheerdersList()\">\n</code></pre>\n\n<p>The difficulty with Flex is to understand how a mxml component maps the equivalent pure actionscript class. When you have in your mxml code something like <local:Mycomponent id=\"myComponent\">, this add as child an instance of a class. The mxml file, Mycomponent.mxml, defines the class. Unless declared as static, the functions that are listed within the <mx:Script> tag are functions that apply on the instance. There is no constructor that you can explicitly define but the instance is not available before actual creation. You therefore have to rely on creationComplete to execute any function that you would have called from a constructor function in a strictly AS3 class. </p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21238/"
] |
I'm building my first flex app and am currently bussy splitting it up in multiple components to make it maintainable.
I have a screen which holds a list that is displayed and filled after a succesfull login attempt:
Part of the main app:
```
<mx:ViewStack id="vsAdmin" height="100%" width="100%">
<mx:TabNavigator id="adminTabs" width="100%" height="100%" historyManagementEnabled="false">
<myComp:compBeheerdersAdmin id="beheerdersViewstackA"/>
</mx:TabNavigator>
</mx:ViewStack>
```
In the component compBeheerdersAdmin there is a function requestBeheerdersList() that gets the data from the server and Binds it to the list through a handler.
After login the following code from the main app:
```
mainViewstack.selectedChild = vsAdmin;
//beheerdersViewstackA.createComponentsFromDescriptors();
beheerdersViewstackA.requestBeheerdersList();
```
The function requestBeheerdersList() does nothing (is not reached, i put a alert as first statement in the function but that is not displayed) when i login after a fresh load of the swf, but when i logout and login again, then the function is reached and the alert is displayed and the list is filled with the data from the server.
Any ideas?
|
I would make sure the component exists that you are calling before calling the next function. This could be done by forcing creationPolicy=all as you figured out. You could also add an event listener for the CreationComplete to call the function you want:
```
private function doThisFirst():void{
mainViewstack.selectedChild = vsAdmin;
vsAdmin.addEventListener(FlexEvent.CREATION_COMPLETE,doThis);
}
private function doThis():void{
beheerdersViewstackA.requestBeheerdersList();
}
```
This may not be exactly correct but I tried to recreate to your specific example. If you are familiar with viewstack creation of its children and eventlisteners you should be able to fit this to your specific need.
|
197,802 |
<p>I have an Access DB that I would like to extract the source code from so I can put it into Source control. </p>
<p>I have tried to extract the data using the Primary Interop Assemblies(PIA), but I am getting issues as it is not picking up all of the modules and forms. </p>
<p>There are 140 Forms and Modules in the code(Don't ask, it's a legacy system I have inherited) but the PIA code is only picking up 91 of them. </p>
<p>Here is the code I am using. </p>
<pre><code>using System;
using Microsoft.Office.Interop.Access;
namespace GetAccesSourceFiles
{
class Program
{
static void Main(string[] args)
{
ApplicationClass appClass = new ApplicationClass();
try
{
appClass.OpenCurrentDatabase("C:\\svn\\projects\\db.mdb",false,"");
Console.WriteLine(appClass.Version);
Console.WriteLine(appClass.Modules.Count.ToString());
Console.WriteLine(appClass.Modules.Parent.ToString());
int NumOfLines = 0;
for (int i = 0; i < appClass.Modules.Count; i++)
{
Console.WriteLine(appClass.Modules[i].Name + " : " + appClass.Modules[i].CountOfLines);
NumOfLines += appClass.Modules[i].CountOfLines;
}
Console.WriteLine("Number of Lines : " + NumOfLines);
Console.ReadKey();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message + "\r\n" +ex.StackTrace);
}
finally
{
appClass.CloseCurrentDatabase();
appClass.Quit(AcQuitOption.acQuitSaveNone);
}
}
}
}
</code></pre>
<p>Any suggestions on what that code might be missing? or on a product/tool out there that will do this for me?</p>
<p>Edit:
I should also mention that this needs to script to disk, integration with VSS is not an option as our source system is SVN. Thanks.</p>
|
[
{
"answer_id": 197825,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 1,
"selected": false,
"text": "<p>There is a better way. You can use Visual Sourcesafe (and possibly other SCCs) to version control code and objects in place: see this <a href=\"http://msdn.microsoft.com/en-us/library/ms181088(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN article</a></p>\n"
},
{
"answer_id": 197868,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": "<p>This may help:</p>\n\n<pre><code> Sub AllCodeToDesktop()\n 'The reference for the FileSystemObject Object is Windows Script Host Object Model\n 'but it not necessary to add the reference for this procedure.\n\n Dim fs As Object\n Dim f As Object\n Dim strMod As String\n Dim mdl As Object\n Dim i As Integer\n\n Set fs = CreateObject(\"Scripting.FileSystemObject\")\n\n 'Set up the file.\n Set f = fs.CreateTextFile(SpFolder(\"Desktop\") & \"\\\" _\n & Replace(CurrentProject.Name, \".\", \"\") & \".txt\")\n\n 'For each component in the project ...\n For Each mdl In VBE.ActiveVBProject.VBComponents\n 'using the count of lines ...\n i = VBE.ActiveVBProject.VBComponents(mdl.Name).CodeModule.CountOfLines\n 'put the code in a string ...\n If VBE.ActiveVBProject.VBComponents(mdl.Name).codemodule.CountOfLines > 0 Then\n strMod = VBE.ActiveVBProject.VBComponents(mdl.Name).codemodule.Lines(1, i)\n End If\n 'and then write it to a file, first marking the start with\n 'some equal signs and the component name.\n f.writeline String(15, \"=\") & vbCrLf & mdl.Name _\n & vbCrLf & String(15, \"=\") & vbCrLf & strMod\n Next\n\n 'Close eveything\n f.Close\n Set fs = Nothing\n End Sub\n\n Function SpFolder(SpName As String)\n 'Special folders\n SpFolder = CreateObject(\"WScript.Shell\").SpecialFolders(SpName)\n End Function \n</code></pre>\n\n<p>From: <a href=\"http://wiki.lessthandot.com/index.php/Code_and_Code_Windows\" rel=\"nofollow noreferrer\">http://wiki.lessthandot.com/index.php/Code_and_Code_Windows</a></p>\n"
},
{
"answer_id": 257990,
"author": "Yarik",
"author_id": 31415,
"author_profile": "https://Stackoverflow.com/users/31415",
"pm_score": 0,
"selected": false,
"text": "<p>You might also want to take a look at his Q&A:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/247292/working-with-multiple-programmers-on-ms-access\">Working with multiple programmers on MS Access</a></p>\n"
},
{
"answer_id": 385821,
"author": "eksortso",
"author_id": 446456,
"author_profile": "https://Stackoverflow.com/users/446456",
"pm_score": 1,
"selected": false,
"text": "<p>You could use the undocumented <strong>Application.SaveAsText</strong> and <strong>Application.LoadFromText</strong> functions. SaveAsText works on modules, forms, and reports; and when you save a form or report as text, its module code will appear at the bottom of the resulting text file.</p>\n\n<p>You could write a routine that would save all of the non-data objects in your Access MDB (or ADP) as text, put it in a module, and just keep that module in a development version of your Access DB. Then you could run the routine and check in the dumped code in VSS.</p>\n\n<p>It's probably not as elegant as the Visual SourceSafe method described by Mitch Wheat, but that depends on what you want to do with the source code. I tend to hang onto multiple versions of MDB's, and use this method to compare source code between them using diff tools such as WinMerge. It's good for porting functionality between branches of development.</p>\n\n<p>It's also good for locating all references to fields or controls wherever they may be found. Viewing Access objects as textual definitions makes finding these references dead simple.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2806/"
] |
I have an Access DB that I would like to extract the source code from so I can put it into Source control.
I have tried to extract the data using the Primary Interop Assemblies(PIA), but I am getting issues as it is not picking up all of the modules and forms.
There are 140 Forms and Modules in the code(Don't ask, it's a legacy system I have inherited) but the PIA code is only picking up 91 of them.
Here is the code I am using.
```
using System;
using Microsoft.Office.Interop.Access;
namespace GetAccesSourceFiles
{
class Program
{
static void Main(string[] args)
{
ApplicationClass appClass = new ApplicationClass();
try
{
appClass.OpenCurrentDatabase("C:\\svn\\projects\\db.mdb",false,"");
Console.WriteLine(appClass.Version);
Console.WriteLine(appClass.Modules.Count.ToString());
Console.WriteLine(appClass.Modules.Parent.ToString());
int NumOfLines = 0;
for (int i = 0; i < appClass.Modules.Count; i++)
{
Console.WriteLine(appClass.Modules[i].Name + " : " + appClass.Modules[i].CountOfLines);
NumOfLines += appClass.Modules[i].CountOfLines;
}
Console.WriteLine("Number of Lines : " + NumOfLines);
Console.ReadKey();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message + "\r\n" +ex.StackTrace);
}
finally
{
appClass.CloseCurrentDatabase();
appClass.Quit(AcQuitOption.acQuitSaveNone);
}
}
}
}
```
Any suggestions on what that code might be missing? or on a product/tool out there that will do this for me?
Edit:
I should also mention that this needs to script to disk, integration with VSS is not an option as our source system is SVN. Thanks.
|
There is a better way. You can use Visual Sourcesafe (and possibly other SCCs) to version control code and objects in place: see this [MSDN article](http://msdn.microsoft.com/en-us/library/ms181088(VS.80).aspx)
|
197,834 |
<p>In particular from this web.config:</p>
<pre><code><configuration>
<configSections>
<section name="RStrace" type="Microsoft.ReportingServices.Diagnostics.RSTraceSectionHandler,Microsoft.ReportingServices.Diagnostics" />
</configSections>
<system.diagnostics>
<switches>
<add name="DefaultTraceSwitch" value="3" />
</switches>
</system.diagnostics>
<RStrace>
<add name="FileName" value="ReportServerService_" />
<add name="FileSizeLimitMb" value="32" />
<add name="KeepFilesForDays" value="14" />
<add name="Prefix" value="appdomain, tid, time" />
<add name="TraceListeners" value="file" />
<add name="TraceFileMode" value="unique" />
<add name="Components" value="all:3" />
</RStrace>
<runtime>
<alwaysFlowImpersonationPolicy enabled="true"/>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.ReportingServices.Interfaces"
publicKeyToken="89845dcd8080cc91"
culture="neutral" />
<bindingRedirect oldVersion="8.0.242.0"
newVersion="10.0.0.0"/>
<bindingRedirect oldVersion="9.0.242.0"
newVersion="10.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
<gcServer enabled="true" />
</runtime>
</configuration>
</code></pre>
|
[
{
"answer_id": 197906,
"author": "Dean Hill",
"author_id": 3106,
"author_profile": "https://Stackoverflow.com/users/3106",
"pm_score": 1,
"selected": false,
"text": "<p>You get this error when you are missing an entry in the configSections area. In the above example, you probably need to add a line similar to this:</p>\n\n<pre><code><section name=\"runtime\" type=\"your-datatype\"/>\n</code></pre>\n"
},
{
"answer_id": 197909,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>It's saying that it's finding the <runtime> tag in you file, but doesn't know what to do with it. It may be in the wrong section.</p>\n\n<p>As <runtime> is a standard web.config element, something screwy is going on. Try removing the RTrace section. If that works, restore the Rtrace section after the runtime section.</p>\n"
},
{
"answer_id": 402639,
"author": "James",
"author_id": 11604,
"author_profile": "https://Stackoverflow.com/users/11604",
"pm_score": 2,
"selected": true,
"text": "<p>It looks like .NET was installed using a corporate re-packaging technology and not all the bits were there. We installed from the original Microsoft image and all is fine.</p>\n"
},
{
"answer_id": 50462056,
"author": "Mohammed Arabiat",
"author_id": 2542468,
"author_profile": "https://Stackoverflow.com/users/2542468",
"pm_score": 2,
"selected": false,
"text": "<p>In my case, I have found that the <code>machine.config</code> file was missing. It should be located in <code>C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\Config</code> on my machine. There existed a <code>machine.config.defaults</code> in the same directory. I made a copy of the file in the same directory and renamed it to <code>machine.config</code>. Applications loaded normally afterwards for me.</p>\n\n<p>I discovered the absence of the <code>machine.config</code> file through use of the <a href=\"https://blogs.msdn.microsoft.com/astebner/2008/10/13/net-framework-setup-verification-tool-users-guide/\" rel=\"nofollow noreferrer\">.NET Framework Setup Verification Tool</a>. After running it for .NET framework 4.7.1, a log file in <code>%temp%</code> shows up whose name starts with <code>setupverifier_errors</code>. It contains a list of files that are missing and <code>machine.config</code> was on top of the list. If restoring <code>machine.config</code> did not fix it for you, it might be worth it to check other files listed in the log file.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11604/"
] |
In particular from this web.config:
```
<configuration>
<configSections>
<section name="RStrace" type="Microsoft.ReportingServices.Diagnostics.RSTraceSectionHandler,Microsoft.ReportingServices.Diagnostics" />
</configSections>
<system.diagnostics>
<switches>
<add name="DefaultTraceSwitch" value="3" />
</switches>
</system.diagnostics>
<RStrace>
<add name="FileName" value="ReportServerService_" />
<add name="FileSizeLimitMb" value="32" />
<add name="KeepFilesForDays" value="14" />
<add name="Prefix" value="appdomain, tid, time" />
<add name="TraceListeners" value="file" />
<add name="TraceFileMode" value="unique" />
<add name="Components" value="all:3" />
</RStrace>
<runtime>
<alwaysFlowImpersonationPolicy enabled="true"/>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.ReportingServices.Interfaces"
publicKeyToken="89845dcd8080cc91"
culture="neutral" />
<bindingRedirect oldVersion="8.0.242.0"
newVersion="10.0.0.0"/>
<bindingRedirect oldVersion="9.0.242.0"
newVersion="10.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
<gcServer enabled="true" />
</runtime>
</configuration>
```
|
It looks like .NET was installed using a corporate re-packaging technology and not all the bits were there. We installed from the original Microsoft image and all is fine.
|
197,839 |
<p>This question was inspired by a similar question: <a href="https://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array">How does delete[] “know” the size of the operand array?</a></p>
<p>My question is a little different: <strong>Is there any way to determine the size of a C++ array programmatically? And if not, why?</strong> Every function I've seen that takes an array also requires an integer parameter to give it the size. But as the linked question pointed out, <code>delete[]</code> must know the size of the memory to be deallocated.</p>
<p>Consider this C++ code:</p>
<pre><code>int* arr = new int[256];
printf("Size of arr: %d\n", sizeof(arr));
</code></pre>
<p>This prints "<code>Size of arr: 4</code>", which is just the size of the pointer. It would be nice to have some function which prints 256, but I don't think one exists in C++. (Again, part of the question is why it doesn't exist.)</p>
<p><strong>Clarification</strong>: I know that if I declared the array on the stack instead of the heap (i.e. "<code>int arr[256];</code>") that the <code>sizeof</code> operator would return 1024 (array length * sizeof(int)).</p>
|
[
{
"answer_id": 197857,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 3,
"selected": false,
"text": "<p>Common way to handle this is to either use a vector</p>\n\n<pre><code>int main()\n{\n std::vector<int> v(256);\n printf(\"size of v is %i capacity is %i\\n\", sizeof(int) * v.size(), sizeof(int) * v.capacity());\n}\n</code></pre>\n\n<p>or predefine the size</p>\n\n<pre><code>const int arrSize = 256;\nint main()\n{\n int array[arrSize];\n printf(\"Size of array is %i\", sizeof(int) * arrSize);\n}\n</code></pre>\n"
},
{
"answer_id": 197860,
"author": "Peter Kühne",
"author_id": 27351,
"author_profile": "https://Stackoverflow.com/users/27351",
"pm_score": 2,
"selected": false,
"text": "<p>That's because your variable arr is only a pointer. It holds the address of a particular location in memory, without knowing anything about it. You declare it to be int*, which gives the compiler some indication of what to do when you increment the pointer. Other than that, you could be pointing into the beginning or the end of the array or into the stack or into invalid memory. \nBut I agree with you, not being able to call sizeof is very annoying :)</p>\n\n<p>QuantumPete</p>\n"
},
{
"answer_id": 197865,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 1,
"selected": false,
"text": "<p>No, there isn't any way to do this, you have to keep track of how big it is externally. Classes like <code>std::vector</code> do this for you.</p>\n"
},
{
"answer_id": 197872,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "<p>No, there is no way to do that in Standard C++. </p>\n\n<p>There is no really good reason why not that I'm aware of. Probably, the size was considered an implementation detail, and best not exposed. Note that when you say malloc(1000), there is no guarantee that the block returned is 1000 bytes --- only that it's <em>at least</em> 1000 bytes. Most likely it's about 1020 (1K minus 4 bytes for overhead). In that case, the \"1020\" size is the important one for the run-time library to remember. And of course, that would change between implementations.</p>\n\n<p>Which is why the Standards committee added std:vector<>, which does keep track of it exact size.</p>\n"
},
{
"answer_id": 197900,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 7,
"selected": true,
"text": "<p><code>delete []</code> does know the size that was allocated. However, that knowledge resides in the runtime or in the operating system's memory manager, meaning that it is not available to the compiler during compilation. And <code>sizeof()</code> is not a real function, it is actually evaluated to a constant by the compiler, which is something it cannot do for dynamically allocated arrays, whose size is not known during compilation.</p>\n\n<p>Also, consider this example:</p>\n\n<pre><code>\nint *arr = new int[256];\nint *p = &arr[100];\nprintf(\"Size: %d\\n\", sizeof(p));\n</code></pre>\n\n<p>How would the compiler know what the size of <code>p</code> is? The root of the problem is that arrays in C and C++ are not first-class objects. They decay to pointers, and there is no way for the compiler or the program itself to know whether a pointer points to the beginning of a chunk of memory allocated by <code>new</code>, or to a single object, or to some place in the middle of a chunk of memory allocated by <code>new</code>.</p>\n\n<p>One reason for this is that C and C++ leave memory management to the programmer and to the operating system, which is also why they do not have garbage collection. Implementation of <code>new</code> and <code>delete</code> is not part of the C++ standard, because C++ is meant to be used on a variety of platforms, which may manage their memory in very different ways. It may be possible to let C++ keep track of all the allocated arrays and their sizes if you are writing a word processor for a windows box running on the latest Intel CPU, but it may be completely infeasible when you are writing an embedded system running on a DSP.</p>\n"
},
{
"answer_id": 197901,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>You can't, fundamentally:</p>\n\n<pre><code>void foo(int* arr);\n\nint arr[100] = {0};\n\nfoo(arr+1); // Calls foo with a pointer to 100-1 elements.\n</code></pre>\n\n<p>A C++ array is nothing more than a collection of objects which are stored in a contiguous memory region. Since there are no holes betweeen them (padding is <em>inside</em> objects), you can find the next element of an array by simply incerementing the pointer. At CPU level, this is a simple adjustment. C++ only inserts a sizeof(element) multiplier.</p>\n\n<p>Note that implementations may choose to implement \"fat pointers\" which contain array bounds. They'd need to be twice as big, as you'd need to link to some kind of \"array bound descriptor\". As a side effect, on such implementations you could be able to call <code>delete [] (1+new int[5]);</code></p>\n"
},
{
"answer_id": 197905,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately, this is not possible. In C and C++, it is the responsibility of the programmer to remember of the length of an array since array length is not stored anywhere. Delete[] and free() does remember the size of the allocated block but they might allocate more memory than requested so their internal data structures storing the sizes of allocated memory blocks might not give you the exact size of the your array.</p>\n\n<p>Note that C++ STL vectors, which are basically arrays wrapped in a class with some helper functions, do store the length of the array so if you really need this functionality, you could just use vectors.</p>\n"
},
{
"answer_id": 197907,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 2,
"selected": false,
"text": "<p>There is no portable way of determining the size of a dynamically-allocated array in C++ given only its pointer. C++ is made to be very flexible and to give power to the user. For example, the standard does not define how memory allocators must work, e.g. by adding a required size header. Not requiring a header allows for a lot more flexibility. </p>\n\n<p>As one example, consider a string implemented as a char * array. It's common to use pointers into the middle of the array to pick out substrings. As an example, see the strtok function in the standard C library. If some header were required to be embedded just before each array, you'd need to trash portions of the array before the substring. </p>\n\n<p>An alternative way to handle the headers would be to have array headers in one block of memory and have them point to the raw array memory elsewhere. In many situations, this would require two pointer lookups for each reference, which would be a big drag on performance. There are ways of overcoming these deficiencies, but they add complexity and reduce implementation flexibility. </p>\n\n<p>The std::vector template is my favorite way of keeping the size of an array bound to the array itself.</p>\n\n<p>C is portable assembly language with a better syntax. </p>\n"
},
{
"answer_id": 197914,
"author": "James Rose",
"author_id": 9703,
"author_profile": "https://Stackoverflow.com/users/9703",
"pm_score": 1,
"selected": false,
"text": "<p>In general, no. Arrays in C and C++ are just blocks of memory with no bookkeeping information attached. Without storing the length of the array in memory, and adding overhead to do so, it is impossible in the general case.</p>\n\n<p>There is an exception for arrays that are statically allocated. For instance, if you declare: <code>int a[50]</code> then <code>sizeof(a)</code> will work. This is possible because the [50] is part of the static type of the array: it is known to the compiler. sizeof is interpreted at compile time.</p>\n\n<p>However, if you create a pointer: <code>int *p = a</code>, then <code>sizeof(p)</code> will return the size of the pointer as you mention, not the size of the array, because the compiler does not know what p points to. </p>\n"
},
{
"answer_id": 198018,
"author": "Mykelyk",
"author_id": 27456,
"author_profile": "https://Stackoverflow.com/users/27456",
"pm_score": 2,
"selected": false,
"text": "<p>C++ decided to add new to do a typesafe malloc, than new must know both size e numbers of elements for calling ctors, so delete for calling dtors. In the early days you have to actually pass to delete the numbers a objects you passed to new.</p>\n\n<pre><code>string* p = new string[5];\ndelete[5] p;\n</code></pre>\n\n<p>However they thought that if use new<type>[] the overhead of a number was small. So they decided that new[n] must remember n and pass it to delete. There are three main ways to implement it.</p>\n\n<ol>\n<li>keep a hash-table of pointer to size</li>\n<li>wrote it directly near the vector</li>\n<li>do something completely different</li>\n</ol>\n\n<p>Maybe is possible to obtain the size like that:</p>\n\n<pre><code>size_t* p = new size_t[10];\ncout << p[-1] << endl;\n// Or\ncout << p[11] << endl;\n</code></pre>\n\n<p>Or hell none of those.</p>\n"
},
{
"answer_id": 198116,
"author": "João Augusto",
"author_id": 6909,
"author_profile": "https://Stackoverflow.com/users/6909",
"pm_score": 4,
"selected": false,
"text": "<p>Well there is actually a way to determine the size, but it's not \"safe\" and will be diferent from compiler to compiler.... <strong>so it shouldn't be used at all</strong>.</p>\n\n<p>When you do:\nint* arr = new int[256]; </p>\n\n<p>The 256 is irrelevant you will be given 256*sizeof(int) assuming for this case 1024, this value will be stored probably at ( arr - 4 )</p>\n\n<p>So to give you the number of \"items\"</p>\n\n<p>int* p_iToSize = arr - 4;</p>\n\n<p>printf(\"Number of items %d\", *p_iToSize / sizeof(int));</p>\n\n<p>For every malloc, new, whatever before the continuos memory block that you receive, there is also allocated a space reserved with some information regarding the block of memory you were given.</p>\n"
},
{
"answer_id": 206372,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is there any way to determine the size of a C++ array programmatically? And if not, why?</p>\n</blockquote>\n\n<ol>\n<li>No, unless you keep track of it yourself.</li>\n<li>Because if the compiler doesn't have to tell anyone besides itself about that information it constrains the compiler less. Whether that is desirable or not is up to debate.</li>\n</ol>\n"
},
{
"answer_id": 206381,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 0,
"selected": false,
"text": "<p>@Dima,</p>\n\n<blockquote>\n <p>How would the compiler know what the size of p is?</p>\n</blockquote>\n\n<p>The compiler has to know the size of p; otherwise, it cannot implement <code>delete[]</code>. The compiler doesn't need to tell anyone else how it figures that out.</p>\n\n<p>For a fun way to verify this, compare the pointer returned by <code>operator new[]</code> to the pointer returned by <code>new[]</code>.</p>\n"
},
{
"answer_id": 419928,
"author": "SMeyers",
"author_id": 28954,
"author_profile": "https://Stackoverflow.com/users/28954",
"pm_score": 0,
"selected": false,
"text": "<p>The compiler can't know that </p>\n\n<pre><code>char *ar = new char[100] \n</code></pre>\n\n<p>is an array of 100 characters because it doesn't create an actual array in memory it just creates a pointer to 100 uninitialized bytes in memory. </p>\n\n<p>If you want to know the size of the given array just use std::vector.\nstd::vector is a better array simply.</p>\n"
},
{
"answer_id": 12502434,
"author": "MessyCode",
"author_id": 1565515,
"author_profile": "https://Stackoverflow.com/users/1565515",
"pm_score": 0,
"selected": false,
"text": "<p>When you create array pointers (Create wrapper with template to pointers) you can't but when you create array of object,\nYou can get the size of the array like that:</p>\n\n<pre><code>char* chars=new char[100];\nprintf(\"%d\",*((int*)chars-1));\n</code></pre>\n\n<p>The <code>delete[]</code> function need to deconstruct all the objects in it. to do it the <code>new[]</code> keyword puts the number of elements behind all of the array.</p>\n\n<p>The body of array is like that:</p>\n\n<pre><code>int count;\nObjectType* data; //This value is returned when using new[]\n</code></pre>\n"
},
{
"answer_id": 13089601,
"author": "PER",
"author_id": 1777503,
"author_profile": "https://Stackoverflow.com/users/1777503",
"pm_score": -1,
"selected": false,
"text": "<p>You could just create an extra element of the array and then apply the most unlikely number that will be stored in the array. Then you can determine the number of elements through some function by passing that number. </p>\n\n<p>In the case of declaring and initializing an array at the moment of creation, you can then scan it and then generate a number that does not match any of the elements of the array. But if you then modify one of the elements, you will not know if that element stores the same value as the last element, so you will then have to generate a new number to store in the last element.. Going through all that, you might as well just store the total number of elements at the moment of creation in a variable. And that will probably be the case if you only use the array within a function.</p>\n"
},
{
"answer_id": 16568872,
"author": "bearvarine",
"author_id": 1952060,
"author_profile": "https://Stackoverflow.com/users/1952060",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on your application, you could create a \"sentinel value\" at the end of your array.</p>\n\n<p>The sentinel value must have some unique property.</p>\n\n<p>You can then either process the array (or do a linear search) for the sentinel value, counting as you go. Once you reach the sentinel value, you have your array count.</p>\n\n<p>For a simple C string, the terminating \\0 is an example of a sentinel value.</p>\n"
},
{
"answer_id": 17014793,
"author": "Zingam",
"author_id": 1474291,
"author_profile": "https://Stackoverflow.com/users/1474291",
"pm_score": 2,
"selected": false,
"text": "<p>Some magic:</p>\n\n<pre><code>template <typename T, size_t S>\ninline\nsize_t array_size(const T (&v)[S]) \n{ \n return S; \n}\n</code></pre>\n\n<p>And this is how we do it in C++11:</p>\n\n<pre><code>template<typename T, size_t S>\nconstexpr \nauto array_size(const T (&)[S]) -> size_t\n{ \n return S; \n}\n</code></pre>\n"
},
{
"answer_id": 20436733,
"author": "Brent Faust",
"author_id": 225240,
"author_profile": "https://Stackoverflow.com/users/225240",
"pm_score": 2,
"selected": false,
"text": "<p>Now there is <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow\">std::array</a>, an efficient compile-time wrapper around a constant-size array:</p>\n\n<pre><code>#include <array>\n\nint main (int argc, char** argv)\n{\n std::array<int, 256> arr;\n printf(\"Size of arr: %ld\\n\", arr.size());\n}\n</code></pre>\n\n<p>The parameters are <code><type, #elements></code>.</p>\n\n<p>You also get a few other niceties, like iterators, empty(), and max_size().</p>\n"
},
{
"answer_id": 27894696,
"author": "user4443767",
"author_id": 4443767,
"author_profile": "https://Stackoverflow.com/users/4443767",
"pm_score": 0,
"selected": false,
"text": "<p>the way I do that is by dividing the size of the array by the size of the first element</p>\n\n<pre><code>int intarray[100];\nprintf (\"Size of the array %d\\n\", (sizeof(intarray) / sizeof(intarray[0]));\n</code></pre>\n\n<p>It prints 100</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
This question was inspired by a similar question: [How does delete[] “know” the size of the operand array?](https://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array)
My question is a little different: **Is there any way to determine the size of a C++ array programmatically? And if not, why?** Every function I've seen that takes an array also requires an integer parameter to give it the size. But as the linked question pointed out, `delete[]` must know the size of the memory to be deallocated.
Consider this C++ code:
```
int* arr = new int[256];
printf("Size of arr: %d\n", sizeof(arr));
```
This prints "`Size of arr: 4`", which is just the size of the pointer. It would be nice to have some function which prints 256, but I don't think one exists in C++. (Again, part of the question is why it doesn't exist.)
**Clarification**: I know that if I declared the array on the stack instead of the heap (i.e. "`int arr[256];`") that the `sizeof` operator would return 1024 (array length \* sizeof(int)).
|
`delete []` does know the size that was allocated. However, that knowledge resides in the runtime or in the operating system's memory manager, meaning that it is not available to the compiler during compilation. And `sizeof()` is not a real function, it is actually evaluated to a constant by the compiler, which is something it cannot do for dynamically allocated arrays, whose size is not known during compilation.
Also, consider this example:
```
int *arr = new int[256];
int *p = &arr[100];
printf("Size: %d\n", sizeof(p));
```
How would the compiler know what the size of `p` is? The root of the problem is that arrays in C and C++ are not first-class objects. They decay to pointers, and there is no way for the compiler or the program itself to know whether a pointer points to the beginning of a chunk of memory allocated by `new`, or to a single object, or to some place in the middle of a chunk of memory allocated by `new`.
One reason for this is that C and C++ leave memory management to the programmer and to the operating system, which is also why they do not have garbage collection. Implementation of `new` and `delete` is not part of the C++ standard, because C++ is meant to be used on a variety of platforms, which may manage their memory in very different ways. It may be possible to let C++ keep track of all the allocated arrays and their sizes if you are writing a word processor for a windows box running on the latest Intel CPU, but it may be completely infeasible when you are writing an embedded system running on a DSP.
|
197,845 |
<p>I'm trying to show/hide a movieclip (or graphic) symbol that is on a layer of a button symbol using actionscript 2. Here's what I tried</p>
<p>in the actions for the button:</p>
<pre><code>on (release) {
this.button_name.movieclip_name._alpha = 0;
trace(this.button_name.movieclip_name);
}
</code></pre>
<p>and the trace returns <strong><em>undefined</em></strong>... so I think I've got a problem understanding how to address the child element. However I am not a flash programmer... just hacking on it at the moment for a side project, so I probably just don't understand how it works.</p>
<p>Thanks, Jim :)</p>
|
[
{
"answer_id": 198043,
"author": "Jiaaro",
"author_id": 2908,
"author_profile": "https://Stackoverflow.com/users/2908",
"pm_score": 0,
"selected": false,
"text": "<p>found: <a href=\"http://www.actionscript.org/forums/archive/index.php3/t-99018.html\" rel=\"nofollow noreferrer\">this</a>...</p>\n\n<p>They talk about some 'other way' (other than using button symbols?) Maybe you can use a movieclip symbol as a button?</p>\n"
},
{
"answer_id": 199979,
"author": "fenomas",
"author_id": 10651,
"author_profile": "https://Stackoverflow.com/users/10651",
"pm_score": 2,
"selected": true,
"text": "<p>For AS2, it's not a good idea to put MovieClips inside buttons. The easiest and most direct approach is to restructure things so that your button and the movieclip you had inside it are at the same level, perhaps within a new MC created to contain them. You should think of the Button symbol as a thing that only provides a clickable hit state, but is not a container for other things.</p>\n\n<p>As for your followup, yep, you can indeed use MovieClips as buttons. If you give your MC functions to handle button-like events (onPress, onRelease, onReleaseOutside and so on), those functions will get called just like on a Button. You can also control the finer details - see the docs on MovieClip.hitArea and MovieClip.useHandCursor.</p>\n\n<p>One thing I've done frequently is to create frames in the MC called \"show\" and \"hide\", followed by short animations and a \"stop()\" command, and then done something like this:</p>\n\n<pre><code>myMC.onRollOver = function() { gotoAndPlay(\"show\"); }\nmyMC.onRollOut = myMC.onReleaseOutside = function() { gotoAndPlay(\"hide\"); }\nmyMC.onRelease = function() {\n // do something....\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
] |
I'm trying to show/hide a movieclip (or graphic) symbol that is on a layer of a button symbol using actionscript 2. Here's what I tried
in the actions for the button:
```
on (release) {
this.button_name.movieclip_name._alpha = 0;
trace(this.button_name.movieclip_name);
}
```
and the trace returns ***undefined***... so I think I've got a problem understanding how to address the child element. However I am not a flash programmer... just hacking on it at the moment for a side project, so I probably just don't understand how it works.
Thanks, Jim :)
|
For AS2, it's not a good idea to put MovieClips inside buttons. The easiest and most direct approach is to restructure things so that your button and the movieclip you had inside it are at the same level, perhaps within a new MC created to contain them. You should think of the Button symbol as a thing that only provides a clickable hit state, but is not a container for other things.
As for your followup, yep, you can indeed use MovieClips as buttons. If you give your MC functions to handle button-like events (onPress, onRelease, onReleaseOutside and so on), those functions will get called just like on a Button. You can also control the finer details - see the docs on MovieClip.hitArea and MovieClip.useHandCursor.
One thing I've done frequently is to create frames in the MC called "show" and "hide", followed by short animations and a "stop()" command, and then done something like this:
```
myMC.onRollOver = function() { gotoAndPlay("show"); }
myMC.onRollOut = myMC.onReleaseOutside = function() { gotoAndPlay("hide"); }
myMC.onRelease = function() {
// do something....
}
```
|
197,855 |
<p>I have 2 columns in a Grid. When I click a button, I want the first column to animate to the left from it's current position to 0. So, in effect, it collapses and I'm left with just viewing a single column.</p>
|
[
{
"answer_id": 197935,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Shouldn't be too hard. You'd need to create an EventTrigger that has a BeginStoryboard that targets the grid and uses a DoubleAnimation to shrink the column width. <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.animation.doubleanimation.aspx\" rel=\"noreferrer\">The example here has a similar setup.</a> The EventTrigger would go on the button and the DoubleAnimation's <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.animation.storyboard.target.aspx\" rel=\"noreferrer\">StoryBoard.Target</a> would point to the ColumnDefinition you wish to shrink. </p>\n\n<p>Okay, so that doesn't work so well. You can't shrink the column directly, but you CAN set the shrinking column to fill (width=\"*\"), set the width of the Grid and the non-shrinking column, and then shrink the entire grid. This does work. The below example works:</p>\n\n<pre><code><Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n WindowTitle=\"Opacity Animation Example\" \n Background=\"White\">\n <StackPanel Margin=\"20\">\n <Grid Name=\"MyGrid\" Width=\"200\" HorizontalAlignment=\"Left\">\n <Grid.RowDefinitions>\n <RowDefinition Height=\"100\"/>\n </Grid.RowDefinitions>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"100\"/>\n </Grid.ColumnDefinitions>\n <Rectangle HorizontalAlignment=\"Stretch\" \n VerticalAlignment=\"Stretch\" \n Grid.Column=\"0\" Fill=\"Red\"/>\n <Rectangle HorizontalAlignment=\"Stretch\" \n VerticalAlignment=\"Stretch\" \n Grid.Column=\"1\" Fill=\"Blue\"/>\n </Grid>\n\n <Button Name=\"hideButton\">\n <Button.Triggers>\n <EventTrigger RoutedEvent=\"Button.Click\">\n <BeginStoryboard>\n <Storyboard>\n <DoubleAnimation \n Storyboard.TargetName=\"MyGrid\"\n Storyboard.TargetProperty=\"(Grid.Width)\" \n From=\"200\" To=\"100\" \n Duration=\"0:0:2\" \n AutoReverse=\"True\" /> \n </Storyboard>\n </BeginStoryboard>\n </EventTrigger>\n </Button.Triggers>\n </Button>\n </StackPanel>\n</Page>\n</code></pre>\n"
},
{
"answer_id": 198278,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 1,
"selected": false,
"text": "<p>Another thing you can do is animate the contents and set the Grid to autosize to content which it will do smoothly as the contents changes size.</p>\n"
},
{
"answer_id": 198531,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 0,
"selected": false,
"text": "<p>You can also achieve this with GridLength animation , see an example here <a href=\"http://marlongrech.wordpress.com/2007/08/20/gridlength-animation/\" rel=\"nofollow noreferrer\">http://marlongrech.wordpress.com/2007/08/20/gridlength-animation/</a> Using this approach you can manipulate any given Grid.Column or Grid.Row size. </p>\n\n<p>For your special need just put first column with Width=\"Auto\" and second with *, animate the with of the content inside the first column- that will do the trick.</p>\n"
},
{
"answer_id": 3212071,
"author": "Mike Gledhill",
"author_id": 387666,
"author_profile": "https://Stackoverflow.com/users/387666",
"pm_score": 0,
"selected": false,
"text": "<p>I have taken Todd Miranda's C# source code and modified it, to demonstrate how to animate DataGrid Column widths shrinking & expanding.</p>\n\n<p>Here's the source code...</p>\n\n<p><a href=\"http://www.pocketpctoolkit.com/WPF/DataGridColumnWidthAnimation.zip\" rel=\"nofollow noreferrer\">http://www.pocketpctoolkit.com/WPF/DataGridColumnWidthAnimation.zip</a></p>\n\n<p>Basically, you click on a CheckBox, and whichever DataGrid columns have their \"MinWidth\" value set to 0 will be shrunk to zero-width. Click the CheckBox again, the columns will animate back to their original widths.</p>\n\n<p>This WPF code also demonstrates how to create animations / storyboards in code behind. </p>\n"
},
{
"answer_id": 12629636,
"author": "Aaron Hoffman",
"author_id": 47226,
"author_profile": "https://Stackoverflow.com/users/47226",
"pm_score": 3,
"selected": false,
"text": "<p>You need to Create a GridLengthAnimation class (code from: <a href=\"http://windowsclient.net/learn/video.aspx?v=70654\" rel=\"noreferrer\">http://windowsclient.net/learn/video.aspx?v=70654</a>)</p>\n\n<pre><code>public class GridLengthAnimation : AnimationTimeline\n{\n public GridLengthAnimation()\n {\n // no-op\n }\n\n public GridLength From\n {\n get { return (GridLength)GetValue(FromProperty); }\n set { SetValue(FromProperty, value); }\n }\n\n public static readonly DependencyProperty FromProperty =\n DependencyProperty.Register(\"From\", typeof(GridLength), typeof(GridLengthAnimation));\n\n public GridLength To\n {\n get { return (GridLength)GetValue(ToProperty); }\n set { SetValue(ToProperty, value); }\n }\n\n public static readonly DependencyProperty ToProperty =\n DependencyProperty.Register(\"To\", typeof(GridLength), typeof(GridLengthAnimation));\n\n public override Type TargetPropertyType\n {\n get { return typeof(GridLength); }\n }\n\n protected override Freezable CreateInstanceCore()\n {\n return new GridLengthAnimation();\n }\n\n public override object GetCurrentValue(object defaultOriginValue, object defaultDestinationValue, AnimationClock animationClock)\n {\n double fromValue = this.From.Value;\n double toValue = this.To.Value;\n\n if (fromValue > toValue)\n {\n return new GridLength((1 - animationClock.CurrentProgress.Value) * (fromValue - toValue) + toValue, this.To.IsStar ? GridUnitType.Star : GridUnitType.Pixel);\n }\n else\n {\n return new GridLength((animationClock.CurrentProgress.Value) * (toValue - fromValue) + fromValue, this.To.IsStar ? GridUnitType.Star : GridUnitType.Pixel);\n }\n }\n}\n</code></pre>\n\n<p>And a Storyboard for the RowDefinition/ColumnDefinition.</p>\n\n<pre><code><Window.Resources>\n <Storyboard x:Key=\"ColumnAnimation\">\n <Animations:GridLengthAnimation\n BeginTime=\"0:0:0\"\n Duration=\"0:0:0.1\"\n From=\"0*\"\n Storyboard.TargetName=\"ColumnToAnimate\"\n Storyboard.TargetProperty=\"Width\"\n To=\"10*\" />\n </Storyboard>\n\n</Window.Resources>\n\n<Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"10*\" />\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition x:Name=\"ColumnToAnimate\" Width=\"0*\" />\n </Grid.ColumnDefinitions>\n</Grid>\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
I have 2 columns in a Grid. When I click a button, I want the first column to animate to the left from it's current position to 0. So, in effect, it collapses and I'm left with just viewing a single column.
|
Shouldn't be too hard. You'd need to create an EventTrigger that has a BeginStoryboard that targets the grid and uses a DoubleAnimation to shrink the column width. [The example here has a similar setup.](http://msdn.microsoft.com/en-us/library/system.windows.media.animation.doubleanimation.aspx) The EventTrigger would go on the button and the DoubleAnimation's [StoryBoard.Target](http://msdn.microsoft.com/en-us/library/system.windows.media.animation.storyboard.target.aspx) would point to the ColumnDefinition you wish to shrink.
Okay, so that doesn't work so well. You can't shrink the column directly, but you CAN set the shrinking column to fill (width="\*"), set the width of the Grid and the non-shrinking column, and then shrink the entire grid. This does work. The below example works:
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowTitle="Opacity Animation Example"
Background="White">
<StackPanel Margin="20">
<Grid Name="MyGrid" Width="200" HorizontalAlignment="Left">
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Rectangle HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Grid.Column="0" Fill="Red"/>
<Rectangle HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Grid.Column="1" Fill="Blue"/>
</Grid>
<Button Name="hideButton">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="MyGrid"
Storyboard.TargetProperty="(Grid.Width)"
From="200" To="100"
Duration="0:0:2"
AutoReverse="True" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
</StackPanel>
</Page>
```
|
197,864 |
<p>OK, so instead of writing a whole bunch of access control specs, and duplicating them across many of my spec files, I'm looking to create a custom matcher. So instead of this:</p>
<pre><code>describe "access control" do
it "should prevent access by non-logged-in users"
it "should prevent access by normal users"
it "should prevent access by editor users"
it "should prevent access by admin users"
it "should allow access by super admin users"
end
</code></pre>
<p>I want do something like this:</p>
<pre><code>lambda do
get :index
end.should have_access_control(:allowed => [:super_admin], :disallowed => [:admin, :editor, :user])
</code></pre>
<p>Are there any examples or suggestions of how I can go about doing something like this?</p>
|
[
{
"answer_id": 200595,
"author": "Codebeef",
"author_id": 12037,
"author_profile": "https://Stackoverflow.com/users/12037",
"pm_score": 3,
"selected": true,
"text": "<p>OK, <a href=\"http://matthall.wordpress.com/2008/10/14/a-helper-for-testing-access-control-with-rspec/\" rel=\"nofollow noreferrer\">I have found a method of achieving this</a>, though it doesn't use a custom matcher. Include the following code in your spec_helper.rb:</p>\n\n<pre><code>def access_control (code, options={})\n options = {:allow => [], :disallow => []}.merge(options)\n\n options[:allow].each do |user|\n it \"#{code} should allow #{user.to_s}\" do\n login_as(user)\n eval code\n response.should_not redirect_to(login_path)\n end\n end\n\n options[:disallow].each do |user|\n it \"#{code} should disallow #{user.to_s}\" do\n login_as(user)\n eval code\n response.should redirect_to(login_path)\n end\n end\nend\n</code></pre>\n\n<p>And call it as follows:</p>\n\n<pre><code>access_control(\"get :index\", {:allow => [:super_admin], :disallow => [:quentin, :admin]})\n</code></pre>\n\n<p>You can then use it to build up a complete list of methods that should be restricted, and the users to which they are restricted to.</p>\n"
},
{
"answer_id": 405677,
"author": "nakajima",
"author_id": 39589,
"author_profile": "https://Stackoverflow.com/users/39589",
"pm_score": 0,
"selected": false,
"text": "<p>I disagree with your solution. Tests shouldn't be an area to factor out duplication like this. It makes the tests harder to read and harder to maintain. Also, there's certainly an argument to be made that <a href=\"http://evang.eli.st/blog/2008/7/23/when-duplication-in-tests-informs-design\" rel=\"nofollow noreferrer\">duplication in tests can inform your design</a>.</p>\n\n<p>In the initial example you listed, there are 5 different contexts that should each be tested in isolation and able to be understood at a glance. Your solution, while neat, harms these two goals.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12037/"
] |
OK, so instead of writing a whole bunch of access control specs, and duplicating them across many of my spec files, I'm looking to create a custom matcher. So instead of this:
```
describe "access control" do
it "should prevent access by non-logged-in users"
it "should prevent access by normal users"
it "should prevent access by editor users"
it "should prevent access by admin users"
it "should allow access by super admin users"
end
```
I want do something like this:
```
lambda do
get :index
end.should have_access_control(:allowed => [:super_admin], :disallowed => [:admin, :editor, :user])
```
Are there any examples or suggestions of how I can go about doing something like this?
|
OK, [I have found a method of achieving this](http://matthall.wordpress.com/2008/10/14/a-helper-for-testing-access-control-with-rspec/), though it doesn't use a custom matcher. Include the following code in your spec\_helper.rb:
```
def access_control (code, options={})
options = {:allow => [], :disallow => []}.merge(options)
options[:allow].each do |user|
it "#{code} should allow #{user.to_s}" do
login_as(user)
eval code
response.should_not redirect_to(login_path)
end
end
options[:disallow].each do |user|
it "#{code} should disallow #{user.to_s}" do
login_as(user)
eval code
response.should redirect_to(login_path)
end
end
end
```
And call it as follows:
```
access_control("get :index", {:allow => [:super_admin], :disallow => [:quentin, :admin]})
```
You can then use it to build up a complete list of methods that should be restricted, and the users to which they are restricted to.
|
197,867 |
<p>I'm running into a mental roadblock here and I'm hoping that I'm missing something obvious.</p>
<p>Anyway, assume I have a table that looks like this:</p>
<pre>
ID LookupValue SortOrder
============================================
1 A 1000
2 B 2000
3 B 2000
4 C 3000
5 C 4000
</pre>
<p>I'm trying to find, using Linq, places where the <code>LookupValue</code> is the same, but the sort order is different (the <code>ID</code> is a PK on my Database table and is irrelevant to this exercise).</p>
<p>I thought the easiest way would be to group by the <code>LookupValue</code> and the <code>SortOrder</code> and then find places where the <code>LookupValue</code> appears more than twice in the result.</p>
<p>Right now, my code to get the grouped table looks like this:</p>
<pre><code>Dim KeySortPairs = From d In MyDataTable _
Group By Key = d(LookupValue).ToString(), SortOrder = d(SortOrder).ToString() _
Into Group _
Select Key, SortOrder
</code></pre>
<p>Looking in the debug output, the above code produces this result (which is correct):</p>
<pre>
Key SortOrder
================
A 1000
B 2000
C 3000
C 4000
</pre>
<p>To get the duplicate <code>Key</code>'s then, I'm looking through the results like this:</p>
<pre><code>For Each Entry In KeySortPairs.Where(Function(t) t.Key.Count() > 1)
'Multiple Sort Orders!!'
Next
</code></pre>
<p>In this code, however, <em>every</em> entry in the grouped result gets returned. Am I missing something, or shouldn't that count only give me the entries where the <code>Key</code> appears more than once? I assume I'm making a trivial mistake due to my low-level of comfort with VB.NET, but I can't figure it out -- I've tried moving the <code>Count()</code> into a <code>WHERE</code> clause on the Linq expression, but that gave me the same thing.</p>
|
[
{
"answer_id": 197930,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "<p>Key is a string.</p>\n\n<p>Key.Count counts the characters in the string.</p>\n\n<hr>\n\n<p>Change the select to include the group</p>\n\n<pre><code>Select Key, SortOrder, Group\n</code></pre>\n\n<p>and change the where clause to count the group</p>\n\n<pre><code>KeySortPairs.Where(Function(t) t.Group.Count() > 1)\n</code></pre>\n\n<p>Alternatively, counting the group might be overkill. \"Any\" can save time by doing a short enumeration.</p>\n\n<pre><code>KeySortPairs.Where(Function(t) t.Group.Skip(1).Any())\n</code></pre>\n\n<p>(syntax might not be perfect, I don't know vb.linq).</p>\n"
},
{
"answer_id": 197932,
"author": "brien",
"author_id": 4219,
"author_profile": "https://Stackoverflow.com/users/4219",
"pm_score": 0,
"selected": false,
"text": "<p>I think you need a groupby in your for each statement.</p>\n\n<p>Try something like</p>\n\n<pre><code>For Each Entry in KeySortPairs.GroupBy(expression).Where(\n</code></pre>\n"
},
{
"answer_id": 31189170,
"author": "gmail user",
"author_id": 344394,
"author_profile": "https://Stackoverflow.com/users/344394",
"pm_score": 0,
"selected": false,
"text": "<p>It is really old question. I was just trying out. Initially wrote solution in C# and converted to VB.NET by some online converter. Hope doesn't offend any one.</p>\n\n<pre><code> Dim tests As New List(Of test)() From { _\n New test() With { _\n Key.LookUp = \"A\", _\n Key.SortOrder1 = 1000 _\n }, _\n New test() With { _\n Key.LookUp = \"B\", _\n Key.SortOrder1 = 2000 _\n }, _\n New test() With { _\n Key.LookUp = \"B\", _\n Key.SortOrder1 = 2000 _\n }, _\n New test() With { _\n Key.LookUp = \"C\", _\n Key.SortOrder1 = 3000 _\n }, _\n New test() With { _\n Key.LookUp = \"C\", _\n Key.SortOrder1 = 4000 _\n } _\n }\n\n Dim query = From g In From t In testsGroup t By t.LookUpLet firstsortorder = g.First() Where g.Count() > 1 AndAlso g.Any(Function(t1) firstsortorder.SortOrder1 <> t1.SortOrder1)New With { _\n g.Key, _\n Key .result = g _\n}\n\n For Each item As var In query\n Console.WriteLine(\"key \" + item.Key)\n For Each item1 As var In item.result\n Console.WriteLine(vbTab & vbTab & \"sort order \" + item1.SortOrder1)\n Next\n Next\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] |
I'm running into a mental roadblock here and I'm hoping that I'm missing something obvious.
Anyway, assume I have a table that looks like this:
```
ID LookupValue SortOrder
============================================
1 A 1000
2 B 2000
3 B 2000
4 C 3000
5 C 4000
```
I'm trying to find, using Linq, places where the `LookupValue` is the same, but the sort order is different (the `ID` is a PK on my Database table and is irrelevant to this exercise).
I thought the easiest way would be to group by the `LookupValue` and the `SortOrder` and then find places where the `LookupValue` appears more than twice in the result.
Right now, my code to get the grouped table looks like this:
```
Dim KeySortPairs = From d In MyDataTable _
Group By Key = d(LookupValue).ToString(), SortOrder = d(SortOrder).ToString() _
Into Group _
Select Key, SortOrder
```
Looking in the debug output, the above code produces this result (which is correct):
```
Key SortOrder
================
A 1000
B 2000
C 3000
C 4000
```
To get the duplicate `Key`'s then, I'm looking through the results like this:
```
For Each Entry In KeySortPairs.Where(Function(t) t.Key.Count() > 1)
'Multiple Sort Orders!!'
Next
```
In this code, however, *every* entry in the grouped result gets returned. Am I missing something, or shouldn't that count only give me the entries where the `Key` appears more than once? I assume I'm making a trivial mistake due to my low-level of comfort with VB.NET, but I can't figure it out -- I've tried moving the `Count()` into a `WHERE` clause on the Linq expression, but that gave me the same thing.
|
Key is a string.
Key.Count counts the characters in the string.
---
Change the select to include the group
```
Select Key, SortOrder, Group
```
and change the where clause to count the group
```
KeySortPairs.Where(Function(t) t.Group.Count() > 1)
```
Alternatively, counting the group might be overkill. "Any" can save time by doing a short enumeration.
```
KeySortPairs.Where(Function(t) t.Group.Skip(1).Any())
```
(syntax might not be perfect, I don't know vb.linq).
|
197,876 |
<p>How do I uninstall a .NET Windows Service if the service files do not exist anymore?</p>
<p>I installed a .NET Windows Service using InstallUtil. I have since deleted the files but forgot to run</p>
<pre><code> InstallUtil /u
</code></pre>
<p>first, so the service is still listed in the Services MMC.</p>
<p>Do I have to go into the registry? Or is there a better way?</p>
|
[
{
"answer_id": 197885,
"author": "Dean Hill",
"author_id": 3106,
"author_profile": "https://Stackoverflow.com/users/3106",
"pm_score": 7,
"selected": false,
"text": "<p>From the command prompt, use the Windows "sc.exe" utility. You will run something like this:</p>\n<pre><code>sc delete <service-name>\n</code></pre>\n<p>If the service name has one or more spaces, surround the name in double quotes (h/t @geoffc):</p>\n<pre><code>sc delete "<service-name>"\n</code></pre>\n"
},
{
"answer_id": 197941,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 11,
"selected": true,
"text": "<p>You have at least three options. I have presented them in order of usage preference.</p>\n\n<p><strong>Method 1</strong> - You can use the <a href=\"http://support.microsoft.com/kb/251192\" rel=\"noreferrer\">SC tool</a> (Sc.exe) included in the Resource Kit. \n(included with Windows 7/8)</p>\n\n<p>Open a Command Prompt and enter</p>\n\n<pre><code>sc delete <service-name>\n</code></pre>\n\n<p>Tool help snippet follows:</p>\n\n<pre><code>DESCRIPTION:\n SC is a command line program used for communicating with the\n NT Service Controller and services.\n\ndelete----------Deletes a service (from the registry).\n</code></pre>\n\n<p><strong>Method 2</strong> - use delserv</p>\n\n<p><a href=\"http://support.microsoft.com/kb/927229\" rel=\"noreferrer\">Download</a> and use delserv command line utility. This is a legacy tool developed for Windows 2000. In current Window XP boxes this was superseded by sc described in method 1.</p>\n\n<p><strong>Method 3</strong> - manually delete registry entries <strong>(Note that this backfires in Windows 7/8)</strong></p>\n\n<p>Windows services are registered under the following registry key.</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\n</code></pre>\n\n<p>Search for the sub-key with the service name under referred key and delete it. (and you might need to restart to remove completely the service from the Services list)</p>\n"
},
{
"answer_id": 14837651,
"author": "ja928",
"author_id": 400271,
"author_profile": "https://Stackoverflow.com/users/400271",
"pm_score": 2,
"selected": false,
"text": "<p>If the original Service .InstallLog and .InstallState files are still in the folder, you can try reinstalling the executable to replace the files, then use InstallUtil /u, then uninstall the program. It's a bit convoluted, but worked in a particular instance for me.</p>\n"
},
{
"answer_id": 17218698,
"author": "Michael",
"author_id": 2506018,
"author_profile": "https://Stackoverflow.com/users/2506018",
"pm_score": 5,
"selected": false,
"text": "<p>Notes on using \"sc delete\" in Windows 8: </p>\n\n<p>1) Open a CMD window with elevated privileges. [Windows Key-X to bring up a menu with the option; select \"Command Prompt (Admin)\".]<br>\n2) Use the parenthetical name from the list in Services [for example, I used \"sc delete gupdate\" when, in Services, it read \"Google Update (gupdate)\"]</p>\n"
},
{
"answer_id": 18962814,
"author": "Robin French",
"author_id": 2312370,
"author_profile": "https://Stackoverflow.com/users/2312370",
"pm_score": 5,
"selected": false,
"text": "<p>Some people mentioning <code>sc delete</code> as an answer. This is how I did it, but it took me a while to find the <code><service-name></code> parameter.</p>\n\n<p>The command <code>sc query type= service</code> (note, it's very particular with formatting, the space before \"service\" is necessary) will output a list of Windows services installed, complete with their qualified name to be used with <code>sc delete <service-name></code> command.</p>\n\n<p>The list is quite long so you may consider piping the output to a text file (i.e. <code>>> C:\\test.txt</code>) and then searching through that.</p>\n\n<p>The <code>SERVICE_NAME</code> is the one to use with <code>sc delete <service-name></code> command.</p>\n"
},
{
"answer_id": 18964610,
"author": "Kevin M",
"author_id": 1838481,
"author_profile": "https://Stackoverflow.com/users/1838481",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Remove Windows Service via Registry</strong></p>\n<p>Its very easy to remove a service from registry if you know the right path. Here is how I did that:</p>\n<ol>\n<li><p>Run <strong>Regedit</strong> or <strong>Regedt32</strong></p>\n</li>\n<li><p>Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"</p>\n</li>\n<li><p>Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).</p>\n</li>\n</ol>\n<p><strong>Delete Windows Service via Command Window</strong></p>\n<p>Alternatively, you can also use command prompt and delete a service using following command:</p>\n<p><strong>sc delete</strong> </p>\n<p>You can also create service by using following command</p>\n<p>sc create "MorganTechService" binpath= "C:\\Program Files\\MorganTechSPace\\myservice.exe"</p>\n<p>Note: You may have to reboot the system to get the list updated in service manager.</p>\n"
},
{
"answer_id": 21926653,
"author": "Mike de Klerk",
"author_id": 1567665,
"author_profile": "https://Stackoverflow.com/users/1567665",
"pm_score": 4,
"selected": false,
"text": "<p>If you wish to use a tool for it you could use <a href=\"http://processhacker.sourceforge.net/\" rel=\"noreferrer\">Process Hacker</a></p>\n\n<p>Form to create the service:</p>\n\n<p><img src=\"https://i.stack.imgur.com/nHjyr.png\" alt=\"Process Hacker Create Service\"></p>\n\n<p>Context menu on a service to delete it:</p>\n\n<p><img src=\"https://i.stack.imgur.com/O1IU2.png\" alt=\"Process Hacker Delete Service\"></p>\n\n<p>I find Process Hacker a more convient tool to manage Windows processes and services than Windows's own Taskmgr.exe. Especially on Windows XP, where you can't access services at all from task manager.</p>\n"
},
{
"answer_id": 24238952,
"author": "user1208639",
"author_id": 1208639,
"author_profile": "https://Stackoverflow.com/users/1208639",
"pm_score": 3,
"selected": false,
"text": "<p>I needed to reinstall my tomcat service, which meant first removing it. This worked for me:</p>\n\n<pre><code>Start a command prompt window using run as administrator\n\nsc query type= service >t.txt\n</code></pre>\n\n<p>(edit the file t.txt, search through the list and find the tomcat service. It's called Tomcat7)</p>\n\n<pre><code>sc delete Tomcat7\n</code></pre>\n\n<p>HOWEVER, the query command did not work the first time, because the tomcat service was not running. It seems to only list services that are running. I had to start the service and run the query command again.</p>\n"
},
{
"answer_id": 27856090,
"author": "Amarjit Singh Chaudhary",
"author_id": 3891385,
"author_profile": "https://Stackoverflow.com/users/3891385",
"pm_score": 0,
"selected": false,
"text": "<p>You can uninstall your windows service by command prompt also just write this piece of command</p>\n\n<pre><code>cd\\ \n\ncd C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319(or version in which you developed your service) \n\ninstallutil c:\\\\xxx.exe(physical path of your service) -d\n</code></pre>\n"
},
{
"answer_id": 29257448,
"author": "Tan",
"author_id": 1462367,
"author_profile": "https://Stackoverflow.com/users/1462367",
"pm_score": 2,
"selected": false,
"text": "<p>You can try running <a href=\"https://technet.microsoft.com/en-us/sysinternals/bb963902.aspx\" rel=\"nofollow\">Autoruns</a>, which would save you from having to edit the registry by hand. This is especially useful when you don't have the needed permissions.</p>\n"
},
{
"answer_id": 34298972,
"author": "Sree",
"author_id": 5635273,
"author_profile": "https://Stackoverflow.com/users/5635273",
"pm_score": 0,
"selected": false,
"text": "<p>1st Step : Move to the Directory where your service is present </p>\n\n<p>Command : cd c:\\xxx\\yyy\\service</p>\n\n<p>2nd Step : Enter the below command </p>\n\n<p>Command : C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\InstallUtil.exe service.exe \\u</p>\n\n<p>Here service.exe is your service exe and \\u will uninstall the service. \nyou'll see \"The uninstall has completed\" message.</p>\n\n<p>If you wanna install a service, Remove \\u in the above command which will install your service </p>\n"
},
{
"answer_id": 41048256,
"author": "barclay",
"author_id": 187423,
"author_profile": "https://Stackoverflow.com/users/187423",
"pm_score": 0,
"selected": false,
"text": "<p>We discovered that even if you run <code>sc_delete</code>, there can be an entry remaining in the registry for your service, so that reinstalling the service results in a corrupted set of registry entries (they don't match). What we did was to <code>regedit</code> and remove this leftover entry by hand.</p>\n\n<p><a href=\"https://i.stack.imgur.com/IDg4u.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IDg4u.png\" alt=\"\"></a>\nNote: ShipmunkService is still showing up after sc_delete!</p>\n\n<p>Then you can reinstall, and your service will run correctly. Best of luck to you all, and may the force be with you.</p>\n"
},
{
"answer_id": 49002662,
"author": "Ayse Özbek",
"author_id": 9417045,
"author_profile": "https://Stackoverflow.com/users/9417045",
"pm_score": 0,
"selected": false,
"text": "<p><code>-Windows+r</code> open cmd.</p>\n\n<p><code>-sc YourSeviceName</code> this code remove your service.</p>\n\n<p><code>-Uninstal \"YourService Path\"</code> this code uninstall your service.</p>\n"
},
{
"answer_id": 65090620,
"author": "Youssef Bouha",
"author_id": 11145237,
"author_profile": "https://Stackoverflow.com/users/11145237",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is to use <a href=\"https://learn.microsoft.com/en-us/sysinternals/downloads/autoruns\" rel=\"nofollow noreferrer\">Sys Internals Autoruns</a></p>\n<p><a href=\"https://i.stack.imgur.com/ecdF2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ecdF2.png\" alt=\"enter image description here\" /></a></p>\n<p>Start it in admin mode and then you can remove obsolete services by delete key</p>\n"
},
{
"answer_id": 70626100,
"author": "Ioannis Batsios",
"author_id": 12839230,
"author_profile": "https://Stackoverflow.com/users/12839230",
"pm_score": 1,
"selected": false,
"text": "<p>Lots of great answers and this really helped me, but there was one thing that was missing. There's a mention of finding the service through cmd with <code>sc query type= service</code> but the problem is that the service I was looking for wasn't running and this command only shows running services (which may be a new feature that didn't exist at the time of the OP answer).</p>\n<p>You have to pass the state of the service to the command like this <code>sc query state= all</code> or <code>sc query state= inactive</code> <em>There's no need to pass the type= service because that is the default</em>.</p>\n<p>And, as stated above, push it to a text file so it's easier to search <code>sc query state= inactive > C:\\servicesStopped.txt</code></p>\n<p>Source: <a href=\"https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/sc-query\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/sc-query</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547/"
] |
How do I uninstall a .NET Windows Service if the service files do not exist anymore?
I installed a .NET Windows Service using InstallUtil. I have since deleted the files but forgot to run
```
InstallUtil /u
```
first, so the service is still listed in the Services MMC.
Do I have to go into the registry? Or is there a better way?
|
You have at least three options. I have presented them in order of usage preference.
**Method 1** - You can use the [SC tool](http://support.microsoft.com/kb/251192) (Sc.exe) included in the Resource Kit.
(included with Windows 7/8)
Open a Command Prompt and enter
```
sc delete <service-name>
```
Tool help snippet follows:
```
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
delete----------Deletes a service (from the registry).
```
**Method 2** - use delserv
[Download](http://support.microsoft.com/kb/927229) and use delserv command line utility. This is a legacy tool developed for Windows 2000. In current Window XP boxes this was superseded by sc described in method 1.
**Method 3** - manually delete registry entries **(Note that this backfires in Windows 7/8)**
Windows services are registered under the following registry key.
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
```
Search for the sub-key with the service name under referred key and delete it. (and you might need to restart to remove completely the service from the Services list)
|
197,893 |
<p>A curious thing happens in Java when you use an abstract class to implement an interface: some of the interface's methods can be completely missing (i.e. neither an abstract declaration or an actual implementation is present), but the compiler does not complain.</p>
<p>For example, given the interface:</p>
<pre><code>public interface IAnything {
void m1();
void m2();
void m3();
}
</code></pre>
<p>the following abstract class gets merrily compiled without a warning or an error:</p>
<pre><code>public abstract class AbstractThing implements IAnything {
public void m1() {}
public void m3() {}
}
</code></pre>
<p>Can you explain why?</p>
|
[
{
"answer_id": 197902,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 7,
"selected": false,
"text": "<p>That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.</p>\n\n<p>Following your example code, try making a subclass of <code>AbstractThing</code> without implementing the <code>m2</code> method and see what errors the compiler gives you. It will force you to implement this method.</p>\n"
},
{
"answer_id": 197961,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 5,
"selected": false,
"text": "<p>Perfectly fine.<br>\n<strong>You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().</strong><br>\nSo <em>if</em> m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile.. </p>\n\n<p><strong>Update</strong>: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)</p>\n"
},
{
"answer_id": 197971,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 1,
"selected": false,
"text": "<p>Abstract classes are not required to implement the methods. So even though it implements an interface, the abstract methods of the interface can remain abstract. If you try to implement an interface in a concrete class (i.e. not abstract) and you do not implement the abstract methods the compiler will tell you: Either implement the abstract methods or declare the class as abstract.</p>\n"
},
{
"answer_id": 19237525,
"author": "Mustakimur Khandaker",
"author_id": 1372772,
"author_profile": "https://Stackoverflow.com/users/1372772",
"pm_score": 2,
"selected": false,
"text": "<p>Interface means a class that has no implementation of its method, but with just declaration.<br/>\nOther hand, abstract class is a class that can have implementation of some method along with some method with just declaration, no implementation.<br/>\nWhen we implement an interface to an abstract class, its means that the abstract class inherited all the methods of the interface. As, it is not important to implement all the method in abstract class however it comes to abstract class (by inheritance too), so the abstract class can left some of the method in interface without implementation here. But, when this abstract class will inherited by some concrete class, they must have to implements all those unimplemented method there in abstract class.</p>\n"
},
{
"answer_id": 29528866,
"author": "Grateful",
"author_id": 3534132,
"author_profile": "https://Stackoverflow.com/users/3534132",
"pm_score": 3,
"selected": false,
"text": "<p>That's fine. To understand the above, you have to understand the nature of abstract classes first. They are similar to interfaces in that respect. This is what Oracle say about this <a href=\"https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html\">here</a>.</p>\n\n<blockquote>\n <p>Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.</p>\n</blockquote>\n\n<p>So you have to think about what happens when an interface extends another interface. For example ...</p>\n\n<pre><code>//Filename: Sports.java\npublic interface Sports\n{\n public void setHomeTeam(String name);\n public void setVisitingTeam(String name);\n}\n\n//Filename: Football.java\npublic interface Football extends Sports\n{\n public void homeTeamScored(int points);\n public void visitingTeamScored(int points);\n public void endOfQuarter(int quarter);\n}\n</code></pre>\n\n<p>... as you can see, this also compiles perfectly fine. Simply because, just like an abstract class, an interface can NOT be instantiated. So, it is not required to explicitly mention the methods from its \"parent\". However, ALL the parent method signatures DO implicitly become a part of the extending interface or implementing abstract class. So, once a proper class (one that can be instantiated) extends the above, it WILL be required to ensure that every single abstract method is implemented. </p>\n\n<p>Hope that helps... and Allahu 'alam !</p>\n"
},
{
"answer_id": 40320804,
"author": "James Grey",
"author_id": 3728901,
"author_profile": "https://Stackoverflow.com/users/3728901",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>When an Abstract Class Implements an Interface</p>\n \n <p>In the section on Interfaces, it was noted that a class that\n implements an interface must implement all of the interface's methods.\n It is possible, however, to define a class that does not implement all\n of the interface's methods, provided that the class is declared to be\n abstract. For example,</p>\n</blockquote>\n\n<pre><code>abstract class X implements Y { \n // implements all but one method of Y\n}\n</code></pre>\n\n<blockquote>\n <p></p>\n</blockquote>\n\n<pre><code>class XX extends X { \n // implements the remaining method in Y \n} \n</code></pre>\n\n<blockquote>\n <p>In this case, class X must be abstract because it does not fully\n implement Y, but class XX does, in fact, implement Y.</p>\n</blockquote>\n\n<p>Reference: <a href=\"http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html\" rel=\"nofollow\">http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html</a></p>\n"
},
{
"answer_id": 45646320,
"author": "sharhp",
"author_id": 1500831,
"author_profile": "https://Stackoverflow.com/users/1500831",
"pm_score": 3,
"selected": false,
"text": "<p>Given the interface:</p>\n\n<pre><code>public interface IAnything {\n int i;\n void m1();\n void m2();\n void m3();\n}\n</code></pre>\n\n<p>This is how Java actually sees it:</p>\n\n<pre><code>public interface IAnything {\n public static final int i;\n public abstract void m1();\n public abstract void m2();\n public abstract void m3();\n}\n</code></pre>\n\n<p>So you can leave some (or all) of these <code>abstract</code> methods unimplemented, just as you would do in the case of <code>abstract</code> classes extending another <code>abstract</code> class.</p>\n\n<p>When you <code>implement</code> an <code>interface</code>, the rule that all <code>interface</code> methods must be implemented in the derived <code>class</code>, applies only to concrete <code>class</code> implementation (i.e., which isn't <code>abstract</code> itself).</p>\n\n<p>If you indeed plan on creating an <code>abstract class</code> out of it, then there is no rule that says you've to <code>implement</code> all the <code>interface</code> methods (note that in such a case it is mandatory to declare the derived <code>class</code> as <code>abstract</code>)</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22904/"
] |
A curious thing happens in Java when you use an abstract class to implement an interface: some of the interface's methods can be completely missing (i.e. neither an abstract declaration or an actual implementation is present), but the compiler does not complain.
For example, given the interface:
```
public interface IAnything {
void m1();
void m2();
void m3();
}
```
the following abstract class gets merrily compiled without a warning or an error:
```
public abstract class AbstractThing implements IAnything {
public void m1() {}
public void m3() {}
}
```
Can you explain why?
|
That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.
Following your example code, try making a subclass of `AbstractThing` without implementing the `m2` method and see what errors the compiler gives you. It will force you to implement this method.
|
197,904 |
<p>I'm in a Microsoft IE environment, but I want to use cygwin for a number of quick scripting tasks.</p>
<p>How would I configure it to use my windows proxy information? Ruby gems, ping, etc are all trying to make direct connections. How can I get them to respect the proxy information that IE and firefox use?</p>
|
[
{
"answer_id": 197934,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 3,
"selected": false,
"text": "<p>I doubt that your corporate firewall allows PING, but the others all appear to be one form of http or another. On a Linux system, you can set your HTTP proxy as an environment variable, so in bash, type:</p>\n\n<pre><code>export http_proxy=http://www.myproxy.com:3128\n</code></pre>\n\n<p>There is a similar environment variable for FTP (ftp_proxy).</p>\n"
},
{
"answer_id": 197947,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 5,
"selected": false,
"text": "<p>Most applications check one of the following environment variables (<code>gem</code> <a href=\"http://docs.rubygems.org/read/chapter/12\" rel=\"noreferrer\">even checks both</a>), so try putting this code in your <code>.bashrc</code>:</p>\n\n<pre><code>proxy=http://host.com:port/\nexport http_proxy=$proxy\nexport HTTP_PROXY=$proxy\n</code></pre>\n"
},
{
"answer_id": 5807110,
"author": "Vlax",
"author_id": 164374,
"author_profile": "https://Stackoverflow.com/users/164374",
"pm_score": 7,
"selected": true,
"text": "<p>Just for the records if you need to authenticate to the Proxy use:</p>\n\n<pre><code>export http_proxy=http://username:password@host:port/\n</code></pre>\n\n<p>Taken from: <a href=\"http://samueldotj.blogspot.com/2008/06/configuring-cygwin-to-use-proxy-server.html\">http://samueldotj.blogspot.com/2008/06/configuring-cygwin-to-use-proxy-server.html</a></p>\n"
},
{
"answer_id": 17477659,
"author": "Luis",
"author_id": 1729175,
"author_profile": "https://Stackoverflow.com/users/1729175",
"pm_score": 3,
"selected": false,
"text": "<p>You can also set it on Windows environment variables and <a href=\"https://cygwin.com/cygwin-ug-net/setup-env.html\" rel=\"nofollow noreferrer\">cygwin will load it</a> on startup (little bonus: any command prompt on windows will also have it set).</p>\n"
},
{
"answer_id": 35634635,
"author": "ian0411",
"author_id": 4388883,
"author_profile": "https://Stackoverflow.com/users/4388883",
"pm_score": 3,
"selected": false,
"text": "<p>If I just use what Vlax and Mohsen Nosratinia suggested (<code>export http_proxy=http://yourusername:yourpassword@host:port/</code>), it will only work half of the programs (some of the installs will work but not all) for my company.</p>\n\n<p>By adding another line it will work for all (maybe most) at least in my situation.</p>\n\n<pre><code>export http_proxy=http://yourusername:yourpassword@host:port/\nexport https_proxy=$http_proxy\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13774/"
] |
I'm in a Microsoft IE environment, but I want to use cygwin for a number of quick scripting tasks.
How would I configure it to use my windows proxy information? Ruby gems, ping, etc are all trying to make direct connections. How can I get them to respect the proxy information that IE and firefox use?
|
Just for the records if you need to authenticate to the Proxy use:
```
export http_proxy=http://username:password@host:port/
```
Taken from: <http://samueldotj.blogspot.com/2008/06/configuring-cygwin-to-use-proxy-server.html>
|
197,929 |
<p>What do you think of this kind of code-to-files-mapping?</p>
<pre><code>~/proj/MyClass.ext
~/proj/MyClass:constructors.ext
~/proj/MyClass:properties.ext
~/proj/MyClass:method-one.ext
~/proj/MyClass:method-two:int.ext
~/proj/MyClass:method-two:string.ext
</code></pre>
<p>In a language which is more functional-oriented:</p>
<pre><code>~/proj/definitions.ext
~/proj/function-one.ext
~/proj/function-two:int.ext
~/proj/function-two:string.ext
...
</code></pre>
<p>The point would be that when we are working on our project, we don't <em>see</em> this multiplicity of files.</p>
<p>We might either have some kind of daemon process that keeps a mirror <code>MyClass.ext</code> file perfectly in sync with this bunch of files, or our favorite code editor sees them all but shows them as their logical aggregation, or this kind of conversion only happens as a set of pre+post-commit hooks.</p>
<p>Now, since we wouldn't be interested in this idea's implementation if it's not a good idea, let's not bother ourselves with its implementation details (the how); let's suppose we've got the perfect implementation that would make this idea to <em>work well</em> for us.</p>
<p><strong>What I would like for us to find together is a good list of pros & cons to this <em>approach</em>, both at a high level and at more specific low levels of your concern.</strong></p>
<p>When we'll be done brainstorming this and seeing each answer's votes, we should see easily if this is a good idea or not. <strong>Therefore, please write one pro/con per answer.</strong></p>
<p><strong>EDIT</strong></p>
<p>From all the answers and especially Scott's, I derived that <strong>the only real way my idea might be useful, would be to be able to bring automatic listing of changed <code>class:method</code> couples in the detailed part of each commit-to-vcs message.</strong> This could much more easily be achieved by small scripts run before commits, to update the message template accordingly. </p>
|
[
{
"answer_id": 197950,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>Personally I would find that that type of separation, although possible in some languages, would be a nightmare to maintain, and would make following the code really hard. I personally find that with .NET languages regions in code are far more helpful.</p>\n\n<p>I would be concerned on large projects with the sheer number of files.</p>\n"
},
{
"answer_id": 197955,
"author": "Daniel Jomphe",
"author_id": 25167,
"author_profile": "https://Stackoverflow.com/users/25167",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Pro</strong> Commit changesets should carry much more information about what really happened for this commit to come to life without having to show a diff:</p>\n\n<ul>\n<li>Many files listed for the same class suggest it's been refactored;</li>\n<li>On the opposite, only one file change listed for a class would suggest its behavior has only been slightly modified.</li>\n</ul>\n"
},
{
"answer_id": 197963,
"author": "Daniel Jomphe",
"author_id": 25167,
"author_profile": "https://Stackoverflow.com/users/25167",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Con</strong> On a performance stand-point, all these file I/Os could cost much in big working trees. </p>\n"
},
{
"answer_id": 198055,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 3,
"selected": true,
"text": "<p>Perhaps the better question to ask in response is: What is the problem you would hope to solve with this approach?</p>\n\n<p>The .NET languages support some level of this idea with partial classes, although I've never seen it carried to that extreme and the editing experience is not as seamless as you describe in your \"perfect implementation\".</p>\n\n<p>I can't really see the usefulness of such a scenario. Yes, having multiple files means less <strong>potential</strong> risk of a change affecting other parts of the code but I don't think that outweighs the performance impact of parsing the files to show it as one editable file.</p>\n"
},
{
"answer_id": 198166,
"author": "danpickett",
"author_id": 21788,
"author_profile": "https://Stackoverflow.com/users/21788",
"pm_score": 1,
"selected": false,
"text": "<p>I think like everything it has to be a balance - and it seems like Frameworks are often on either side of the spectrum.</p>\n\n<p>aka Camping vs. Rails et al.</p>\n\n<p>The level of granularity you mapped out above seems a little over the top to me. I foresee refactoring being a nightmare. Even in frameworks like ASP.net and Ruby on Rails, I find myself constantly cleaning up my workspace because I have too many files open and its causing productivity issues.</p>\n\n<ul>\n<li>con: lots of open files when developing</li>\n<li>con: refactoring would be complicated and disorienting</li>\n<li>con: more prone to files breaking naming conventions and interference with actual syntax errors</li>\n<li>con: for interpreted languages, test harnesses would have to include many more files - there would have to be some smart inclusion methods to get everything that was needed to interpret a class.</li>\n<li>con: the filestystem is less representative of an object orientation - sometimes it's nice being able to easily ascertain the classes in a given folder.</li>\n</ul>\n\n<p>Sorry - I want to offer a pro here but it's just not coming to me</p>\n"
},
{
"answer_id": 198209,
"author": "Bryan Anderson",
"author_id": 21186,
"author_profile": "https://Stackoverflow.com/users/21186",
"pm_score": 1,
"selected": false,
"text": "<p>Hard disk space.</p>\n\n<p>On a default windows installation every file takes up at least 4k. Other file systems can take more or less but there's almost always a minimum size. I could see a large software project all of the sudden taking up a large amount of disk space with this system. This might not be a huge problem on the developer's machines but I'd be concerned about the source control server since it seems like servers never have enough disk space.</p>\n"
},
{
"answer_id": 198802,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 1,
"selected": false,
"text": "<p>I agree, this is way too granular. </p>\n\n<p>However, I have considered separating members by scope:</p>\n\n<pre>\nClassA-interface.cs (public members)\nClassA-implementation.cs (non-public members)\n</pre>\n\n<p>Of course, you could go further, but even this bifurcation doesn't \"solve a problem\" that I have. While it would make me more conscious of changes likely to affect client code, I'm better off learning that through tests.</p>\n"
},
{
"answer_id": 198824,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 2,
"selected": false,
"text": "<h3>CON</h3>\n\n<p>Class-per-file lets you wrap your brain around the class as a whole. If your classes are large to the point of being many multi-page monstrosities, you might need to split the methods to separate files, but you might as well refactor and save yourself some maintenance headache. This is one of the arguments against <code>#region</code> as well.</p>\n"
},
{
"answer_id": 198851,
"author": "pk.",
"author_id": 10615,
"author_profile": "https://Stackoverflow.com/users/10615",
"pm_score": 1,
"selected": false,
"text": "<p>PRO: </p>\n\n<p>I've noticed that many GNU C libraries split up their source into 1 function per translation-unit files. From what I gather this is to assist when statically linking the library into a binary. Apparently, when searching for a symbol, the linker will include the entire translation unit in which the symbol resides (which makes sense, since there might be static functions and data in the unit which the symbol depends on). Therefore if you split your code into granular files, its possible that you could keep your static-linked file sizes to a minimum.</p>\n\n<p>I would imagine that in C++ there are fewer benefits, especially for classes with virtual members, as the virtual table would introduce multiple symbol dependencies.</p>\n\n<hr>\n\n<p>CON:</p>\n\n<p>Unless you had built-in IDE support for this mapping it seems that maintainence of anything at the granularity level of methods would be problematic as people make wholesale changes to classes. In projects I work on, functions get will get occasionally renamed in order to more accurately reflect their changing behavior. Adding a file rename on top of the function rename is just one more step for people to screw up.</p>\n"
},
{
"answer_id": 198918,
"author": "Kim Sullivan",
"author_id": 27610,
"author_profile": "https://Stackoverflow.com/users/27610",
"pm_score": 1,
"selected": false,
"text": "<p>Some version control systems, notably Git (and probably BitKeeper), work on this level by design, instead of on a file level.</p>\n\n<p><b>Pro:</b> Especially when refactoring (on branches), this might come in very handy (being able to specify that a single method has moved from one class to another, or that a part of a class has been moved). A system that works on a lower level of granularity than files could resolve merge conflicts easier (because it can track where a method has moved, and can apply the changes accordingly to multiple files).\n<hr>\n<b>Con:</b> I think you really need a VCS that supports it by design, instead of trying to duct-tape it on a file based VCS (Git doesn't work too well on Windows, and BitKeeper is commercial software). Another drawback is that you probably can't do it in a language-agnostic way. AFAIK, Git employs some advanced heuristics to track the individual pieces of content in a file, but it's not infallible, and there might be some languages with nonstandard (not C-like) function/method syntax where conventional heuristics might fail (Prolog predicates).</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25167/"
] |
What do you think of this kind of code-to-files-mapping?
```
~/proj/MyClass.ext
~/proj/MyClass:constructors.ext
~/proj/MyClass:properties.ext
~/proj/MyClass:method-one.ext
~/proj/MyClass:method-two:int.ext
~/proj/MyClass:method-two:string.ext
```
In a language which is more functional-oriented:
```
~/proj/definitions.ext
~/proj/function-one.ext
~/proj/function-two:int.ext
~/proj/function-two:string.ext
...
```
The point would be that when we are working on our project, we don't *see* this multiplicity of files.
We might either have some kind of daemon process that keeps a mirror `MyClass.ext` file perfectly in sync with this bunch of files, or our favorite code editor sees them all but shows them as their logical aggregation, or this kind of conversion only happens as a set of pre+post-commit hooks.
Now, since we wouldn't be interested in this idea's implementation if it's not a good idea, let's not bother ourselves with its implementation details (the how); let's suppose we've got the perfect implementation that would make this idea to *work well* for us.
**What I would like for us to find together is a good list of pros & cons to this *approach*, both at a high level and at more specific low levels of your concern.**
When we'll be done brainstorming this and seeing each answer's votes, we should see easily if this is a good idea or not. **Therefore, please write one pro/con per answer.**
**EDIT**
From all the answers and especially Scott's, I derived that **the only real way my idea might be useful, would be to be able to bring automatic listing of changed `class:method` couples in the detailed part of each commit-to-vcs message.** This could much more easily be achieved by small scripts run before commits, to update the message template accordingly.
|
Perhaps the better question to ask in response is: What is the problem you would hope to solve with this approach?
The .NET languages support some level of this idea with partial classes, although I've never seen it carried to that extreme and the editing experience is not as seamless as you describe in your "perfect implementation".
I can't really see the usefulness of such a scenario. Yes, having multiple files means less **potential** risk of a change affecting other parts of the code but I don't think that outweighs the performance impact of parsing the files to show it as one editable file.
|
197,933 |
<p>Ideally, something cross-platform.</p>
|
[
{
"answer_id": 197953,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 5,
"selected": true,
"text": "<p>The CPAN is probably the best way to go. Take a look at <a href=\"http://search.cpan.org/~tpaba/Term-Screen-Uni-0.04/lib/Term/Screen/Uni.pm\" rel=\"noreferrer\">Term::Screen:Uni</a>:</p>\n\n<pre><code>require Term::Screen::Uni;\nmy $scr = new Term::Screen::Uni;\n\n$scr->clrscr()\n</code></pre>\n"
},
{
"answer_id": 197956,
"author": "Sec",
"author_id": 20555,
"author_profile": "https://Stackoverflow.com/users/20555",
"pm_score": 3,
"selected": false,
"text": "<p>If you are talking about a terminal, I would use something like the Curses lib to do it.</p>\n\n<p>There is a nice Curses module to access it, which you can use like this:</p>\n\n<pre><code>perl -MCurses -e '$win=new Curses;$win->clear()'\n</code></pre>\n"
},
{
"answer_id": 197984,
"author": "tsee",
"author_id": 13164,
"author_profile": "https://Stackoverflow.com/users/13164",
"pm_score": 4,
"selected": false,
"text": "<p>I generally use <a href=\"http://search.cpan.org/perldoc?Term::ANSIScreen\" rel=\"noreferrer\">Term::ANSIScreen</a> from CPAN which gives me all sorts of useful console-related features.</p>\n\n<pre><code>use Term::ANSIScreen qw(cls);\ncls();\n</code></pre>\n"
},
{
"answer_id": 251441,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<pre><code>print \"\\033[2J\"; #clear the screen\nprint \"\\033[0;0H\"; #jump to 0,0\n</code></pre>\n"
},
{
"answer_id": 2020830,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"http://faq.perl.org/perlfaq8.html\" rel=\"nofollow noreferrer\">perlfaq8</a>'s answer to <a href=\"http://faq.perl.org/perlfaq8.html#How_do_I_clear_the_s\" rel=\"nofollow noreferrer\">How do I clear the screen</a>:</p>\n\n<hr>\n\n<p>To clear the screen, you just have to print the special sequence that tells the terminal to clear the screen. Once you have that sequence, output it when you want to clear the screen.</p>\n\n<p>You can use the Term::ANSIScreen module to get the special sequence. Import the cls function (or the :screen tag):</p>\n\n<pre><code>use Term::ANSIScreen qw(cls);\nmy $clear_screen = cls();\n\nprint $clear_screen;\n</code></pre>\n\n<p>The Term::Cap module can also get the special sequence if you want to deal with the low-level details of terminal control. The Tputs method returns the string for the given capability:</p>\n\n<pre><code>use Term::Cap;\n\n$terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );\n$clear_string = $terminal->Tputs('cl');\n\nprint $clear_screen;\n</code></pre>\n\n<p>On Windows, you can use the Win32::Console module. After creating an object for the output filehandle you want to affect, call the Cls method:</p>\n\n<pre><code>use Win32::Console;\n\n$OUT = Win32::Console->new(STD_OUTPUT_HANDLE);\n$OUT->Cls;\n</code></pre>\n\n<p>If you have a command-line program that does the job, you can call it in backticks to capture whatever it outputs so you can use it later:</p>\n\n<pre><code>$clear_string = `clear`;\n\nprint $clear_string;\n</code></pre>\n"
},
{
"answer_id": 11715174,
"author": "Sebastian M",
"author_id": 1561859,
"author_profile": "https://Stackoverflow.com/users/1561859",
"pm_score": 3,
"selected": false,
"text": "<p>Under OS X and Linux, you can use the following Perl command: </p>\n\n<pre><code>system(\"clear\");\n</code></pre>\n\n<p><strike>Don't know what the equivalent is under Windows.</strike></p>\n\n<p>Edit: Windows equivalent is:</p>\n\n<pre><code>system(\"cls\");\n</code></pre>\n"
},
{
"answer_id": 66672998,
"author": "haxa",
"author_id": 15414604,
"author_profile": "https://Stackoverflow.com/users/15414604",
"pm_score": 1,
"selected": false,
"text": "<p><strong>I disagree with the above</strong></p>\n<ol>\n<li>Connecting additional modules = Increase the attack surface.</li>\n<li>Reduce the Amount of Running Code.</li>\n<li>Code refactoring.</li>\n</ol>\n<hr />\n<pre><code>#!/usr/bin/perl -w\nuse strict;\n\nmy\n( $over, $cleaning );\n( $cleaning ) = qq([J\\033[H\\033[J);\n( $over ) = <<EOF;\n 1. Connecting additional modules = Increase the attack surface.\n 2. Reduce the Amount of Running Code.\n 3. Code refactoring.\nEOF\n\nprint ($cleaning.$over);\n\n__END__\n</code></pre>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>FOO</th>\n<th>BAR</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>\\033</td>\n<td>stands for ESC ANSI value 27</td>\n</tr>\n<tr>\n<td>[J</td>\n<td>erases the screen from the current line down screen</td>\n</tr>\n<tr>\n<td>[H</td>\n<td>move the cursor to the home position</td>\n</tr>\n</tbody>\n</table>\n</div>"
},
{
"answer_id": 67618579,
"author": "Sean Lin",
"author_id": 7624776,
"author_profile": "https://Stackoverflow.com/users/7624776",
"pm_score": 2,
"selected": false,
"text": "<p>Support Linux and Windows:</p>\n<pre><code>system($^O eq 'MSWin32'?'cls':'clear');\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
Ideally, something cross-platform.
|
The CPAN is probably the best way to go. Take a look at [Term::Screen:Uni](http://search.cpan.org/~tpaba/Term-Screen-Uni-0.04/lib/Term/Screen/Uni.pm):
```
require Term::Screen::Uni;
my $scr = new Term::Screen::Uni;
$scr->clrscr()
```
|
197,939 |
<p>I have implemented what I thought was a pretty decent representation of MVC in several web applications but since having joined crackoverflow, I'm finding that perhaps my initial definitions were a bit simplistic and thus I'd really like some clarification on the differences between the Data Access Layer and the Model or Domain Layer of a web application.</p>
<p>For context, I currently use data access objects that implement the CRUD functions for a single record in the table that the object represents as well as a get() function that returns an object that allows me to iterate through all of the objects that met the criteria for the get() function. </p>
<p>These data access objects are referenced directly from the controller scripts which contain my business logic.</p>
<p>If it matters, I'm working in PHP and MySQL but am interested in suggestions that might be coded in other languages.</p>
<p><b>UPDATE:</b> For a more specific example, I have table called user (the convention here is singular table names) which holds such information as email address, active state, user name, password, which company they belong to, etc. This basic object would look like this in code:</p>
<pre><code>class User implements DataAccessObject
{
protected $user_id;
protected $email;
protected $username;
protected $password;
protected $company_id;
protected $active // Bool that holds either a 0 or 1
public function __construct ( $user_id ) // Uses Primary Key to know which record to construct
{
$sql = //Sql to get this information from the database.
// Code necessary to assign member variables their values from the query.
}
public function insert(){}
public function update(){}
public function delete(){}
public static function get($filters, $orderVals, $limit){}
// An object such as user might also contain the following function definition
public static function login($username, $password){}
}
</code></pre>
<p>It sounds like I might have bastardized the DAO Layer and Model layer into a simplified form that combines both any real-world type functions (such as login for a user) with the data access functions. </p>
|
[
{
"answer_id": 198032,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": true,
"text": "<p>The <strong>model</strong> classes stand alone as a good, clean, high-fidelity model of real-world entities. If it's a business domain, they might be customers, plans, products, payments, all that kind of stuff. Your application works with these classes. The idea is that your application is a model of real-world handling of the domain objects. Your application can have method functions that look like verbs people really do, and the implementation of those method functions looks like a real-world description of real-world objects.</p>\n\n<p>Important: This is (ideally) independent of most technical considerations. It's the purest model of the domain objects you can define. [Yes, you do have foreign-key lookup issues, and yes, you do have to make your model objects aware of some data access components so that a model object can find each other objects given just foreign keys instead of the actual object. A good ORM layer handles this navigation issue for you.]</p>\n\n<p>A model full of SQL isn't a good model. The real world isn't full of SQL, either. An invoice is a document with some names and addresses and items, and a shipping date, and a bunch of stuff like that.</p>\n\n<p>The <strong>access</strong> classes handles persistent storage. This usually includes mapping your model objects to relational database tables. A SQL-oriented data access layer would reconstruct your model from a relational database and persist your model in a relational database. A YAML data access layer would read and write YAML files from your model.</p>\n\n<p>Sometimes, the object-relational mapping (ORM) design pattern is used to make a clean separation between SQL's world and your model. Sometimes a Data Access Object (DAO) handles this separation between SQL and model. A ORM or DAO object can be packed full of SQL.</p>\n\n<p>Indeed, when you change database products, the <em>only</em> change is in the DAO or ORM. The model never changes, because it is independent of SQL, YAML, JSON, XML or some other serialization technique.</p>\n\n<p>If your DAO creates and persists model objects, I think you've got the model parts of MVC implemented reasonably well. You can look at ORM packages to get additional ideas of the state of the art. I'm a fan of <a href=\"http://ibatis.apache.org/\" rel=\"noreferrer\">iBatis</a>, myself.</p>\n\n<p>But's only 1/3 of the whole MVC world-view. And -- of course -- purists will tell you that MVC is only desktop or only smalltalk or different from the common web implementation of MVC.</p>\n"
},
{
"answer_id": 198037,
"author": "Milan Novota",
"author_id": 26123,
"author_profile": "https://Stackoverflow.com/users/26123",
"pm_score": 3,
"selected": false,
"text": "<p>It's just a matter of higher abstraction. If you think about some business problem you are about to solve, you want to think about it in terms of concepts (entities, relationships, processes, etc.) of that business, not in terms of database objects or on more detailed level, in terms of internals of some specific database system (eg. MySQL).\nThis way, you can model the domain (ie. the business and its rules) independently on the particular technology you use for implementation.</p>\n\n<p>In other words, when you talk \"data-access-layerish\" you talk about tables, rows, data types, or even about approaches to access these data (eg. by using Active record pattern) while when you talk about about domain, you talk about business objects, business rules and business processes.</p>\n\n<p>And, by the way, when using MVC pattern, you should encapsulate the business logic in your model (domain) level (as I said above), not in controllers - they should just trigger those rules, so to say.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
I have implemented what I thought was a pretty decent representation of MVC in several web applications but since having joined crackoverflow, I'm finding that perhaps my initial definitions were a bit simplistic and thus I'd really like some clarification on the differences between the Data Access Layer and the Model or Domain Layer of a web application.
For context, I currently use data access objects that implement the CRUD functions for a single record in the table that the object represents as well as a get() function that returns an object that allows me to iterate through all of the objects that met the criteria for the get() function.
These data access objects are referenced directly from the controller scripts which contain my business logic.
If it matters, I'm working in PHP and MySQL but am interested in suggestions that might be coded in other languages.
**UPDATE:** For a more specific example, I have table called user (the convention here is singular table names) which holds such information as email address, active state, user name, password, which company they belong to, etc. This basic object would look like this in code:
```
class User implements DataAccessObject
{
protected $user_id;
protected $email;
protected $username;
protected $password;
protected $company_id;
protected $active // Bool that holds either a 0 or 1
public function __construct ( $user_id ) // Uses Primary Key to know which record to construct
{
$sql = //Sql to get this information from the database.
// Code necessary to assign member variables their values from the query.
}
public function insert(){}
public function update(){}
public function delete(){}
public static function get($filters, $orderVals, $limit){}
// An object such as user might also contain the following function definition
public static function login($username, $password){}
}
```
It sounds like I might have bastardized the DAO Layer and Model layer into a simplified form that combines both any real-world type functions (such as login for a user) with the data access functions.
|
The **model** classes stand alone as a good, clean, high-fidelity model of real-world entities. If it's a business domain, they might be customers, plans, products, payments, all that kind of stuff. Your application works with these classes. The idea is that your application is a model of real-world handling of the domain objects. Your application can have method functions that look like verbs people really do, and the implementation of those method functions looks like a real-world description of real-world objects.
Important: This is (ideally) independent of most technical considerations. It's the purest model of the domain objects you can define. [Yes, you do have foreign-key lookup issues, and yes, you do have to make your model objects aware of some data access components so that a model object can find each other objects given just foreign keys instead of the actual object. A good ORM layer handles this navigation issue for you.]
A model full of SQL isn't a good model. The real world isn't full of SQL, either. An invoice is a document with some names and addresses and items, and a shipping date, and a bunch of stuff like that.
The **access** classes handles persistent storage. This usually includes mapping your model objects to relational database tables. A SQL-oriented data access layer would reconstruct your model from a relational database and persist your model in a relational database. A YAML data access layer would read and write YAML files from your model.
Sometimes, the object-relational mapping (ORM) design pattern is used to make a clean separation between SQL's world and your model. Sometimes a Data Access Object (DAO) handles this separation between SQL and model. A ORM or DAO object can be packed full of SQL.
Indeed, when you change database products, the *only* change is in the DAO or ORM. The model never changes, because it is independent of SQL, YAML, JSON, XML or some other serialization technique.
If your DAO creates and persists model objects, I think you've got the model parts of MVC implemented reasonably well. You can look at ORM packages to get additional ideas of the state of the art. I'm a fan of [iBatis](http://ibatis.apache.org/), myself.
But's only 1/3 of the whole MVC world-view. And -- of course -- purists will tell you that MVC is only desktop or only smalltalk or different from the common web implementation of MVC.
|
197,940 |
<p>I can't seem to find an easy to use, .net native way to get Comboboxes on .net winforms to display one value and return another based on the selection without creating my own helper class, with the knowledge that winforms is going to display the ToString method on the object that you put in it.</p>
<p>This is how I'm doing it now, very generically. First, create the helper class.</p>
<pre><code> Public Class ListItem
Public Value As Object
Public DisplayString As String
Public Sub New(ByVal NewValue As Object, ByVal NewDisplayString As String)
Value = NewValue
DisplayString = NewDisplayString
End Sub
Public Overrides Function ToString() As String
Return DisplayString
End Function
End Class
</code></pre>
<p>then, to load the combobox from a collection or whatever.</p>
<pre><code> For Each o as WhateverObject In CollectionIwantToaddItemsFrom
li = New ListItem(o.ValueToReturn, o.ValueToDisplay)
Me.ComboBox1.Items.Add(li)
Next
</code></pre>
<p>and finally, to use the object</p>
<pre><code>Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
if me.combobox1.selecteditem is nothing then exit sub
Dim li As ListItem = me.ComboBox1.SelectedItem
Dim o as object = li.value
'do stuff with o.
end sub
</code></pre>
<p>I'm sure there is something I'm better to use in the framework that I'm over looking. What is it?</p>
|
[
{
"answer_id": 197966,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 1,
"selected": false,
"text": "<p>For lack of better understanding about your application architecture, you're probably taking a good approach.</p>\n\n<p>Normally, I bind the comboboxes to DAL objects where the .ToString() method is overridden. This provides essentially the same feature, though I do have to recast whatever's selected in the combo to its original type to get the \"value\" (usually the property corresponding to the PK of the entity).</p>\n"
},
{
"answer_id": 197967,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>Well, normally, the object you'd place in the Items collection would have their own ToString() which present the object in a presentable form.</p>\n\n<p>If, however, you want to have a completely unrelated string displayed for your object, then you are going to have to do it the way you right.</p>\n"
},
{
"answer_id": 197978,
"author": "Aaron Smith",
"author_id": 12969,
"author_profile": "https://Stackoverflow.com/users/12969",
"pm_score": 0,
"selected": false,
"text": "<p>I usually end up creating a datatable and setting this datatable as the datasource of the combobox. Then I set the DisplayMember to the column I want displayed and the ValueMember to the value I want returned. There may be something better besides datatables, but those are what I use when I need this functionality.</p>\n"
},
{
"answer_id": 198014,
"author": "Sam Meldrum",
"author_id": 16005,
"author_profile": "https://Stackoverflow.com/users/16005",
"pm_score": 4,
"selected": true,
"text": "<p>This is a bit of a hack, but it means you don't have to write your own Name-Value pair class - not a big deal (could be there's something better already in the framework). But what you could do is use the DictionaryEntry class - which is effectively a name value pair. Add the items to a list, then use the DataMember and ValueMember properties on the combobox to bind to the key and value properties of the DictionaryEntry class. Like this:</p>\n\n<pre><code> var list = new List<System.Collections.DictionaryEntry>();\n list.Add(new System.Collections.DictionaryEntry(\"one\", 1));\n list.Add(new System.Collections.DictionaryEntry(\"two\", 2));\n list.Add(new System.Collections.DictionaryEntry(\"three\", 3));\n\n comboBox1.DataSource = list;\n comboBox1.DisplayMember = \"Key\";\n comboBox1.ValueMember = \"Value\";\n</code></pre>\n\n<p>Just realised you prefer the vb dialect. The below does the same for VB :-)</p>\n\n<pre><code>Dim list As List(Of DictionaryEntry)\n\nlist = New List(Of DictionaryEntry)\nlist.Add(New DictionaryEntry(\"One\", 1))\nlist.Add(New DictionaryEntry(\"Two\", 2))\nlist.Add(New DictionaryEntry(\"Three\", 3))\n\nComboBox1.DataSource = list\nComboBox1.DisplayMember = \"Key\"\nComboBox1.ValueMember = \"Value\"\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15769/"
] |
I can't seem to find an easy to use, .net native way to get Comboboxes on .net winforms to display one value and return another based on the selection without creating my own helper class, with the knowledge that winforms is going to display the ToString method on the object that you put in it.
This is how I'm doing it now, very generically. First, create the helper class.
```
Public Class ListItem
Public Value As Object
Public DisplayString As String
Public Sub New(ByVal NewValue As Object, ByVal NewDisplayString As String)
Value = NewValue
DisplayString = NewDisplayString
End Sub
Public Overrides Function ToString() As String
Return DisplayString
End Function
End Class
```
then, to load the combobox from a collection or whatever.
```
For Each o as WhateverObject In CollectionIwantToaddItemsFrom
li = New ListItem(o.ValueToReturn, o.ValueToDisplay)
Me.ComboBox1.Items.Add(li)
Next
```
and finally, to use the object
```
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
if me.combobox1.selecteditem is nothing then exit sub
Dim li As ListItem = me.ComboBox1.SelectedItem
Dim o as object = li.value
'do stuff with o.
end sub
```
I'm sure there is something I'm better to use in the framework that I'm over looking. What is it?
|
This is a bit of a hack, but it means you don't have to write your own Name-Value pair class - not a big deal (could be there's something better already in the framework). But what you could do is use the DictionaryEntry class - which is effectively a name value pair. Add the items to a list, then use the DataMember and ValueMember properties on the combobox to bind to the key and value properties of the DictionaryEntry class. Like this:
```
var list = new List<System.Collections.DictionaryEntry>();
list.Add(new System.Collections.DictionaryEntry("one", 1));
list.Add(new System.Collections.DictionaryEntry("two", 2));
list.Add(new System.Collections.DictionaryEntry("three", 3));
comboBox1.DataSource = list;
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
```
Just realised you prefer the vb dialect. The below does the same for VB :-)
```
Dim list As List(Of DictionaryEntry)
list = New List(Of DictionaryEntry)
list.Add(New DictionaryEntry("One", 1))
list.Add(New DictionaryEntry("Two", 2))
list.Add(New DictionaryEntry("Three", 3))
ComboBox1.DataSource = list
ComboBox1.DisplayMember = "Key"
ComboBox1.ValueMember = "Value"
```
|
197,948 |
<p>I'm using GDI+ in a C++/MFC application and I just can't seem to avoid flickering whenever the window is resized.</p>
<p>I have already tried these steps:</p>
<ul>
<li>returned TRUE on <code>OnEraseBkGnd()</code>;</li>
<li>returned NULL on <code>OnCtlColor()</code>;</li>
<li>used double buffering according to this code:</li>
</ul>
<p></p>
<pre><code>void vwView::OnDraw(CDC* pDC)
{
CRect rcClient;
GetClientRect(rcClient);
Bitmap bmp(rcClient.Width(), rcClient.Height());
Graphics graphics(&bmp);
graphics.DrawImage(m_image, rcClient.left, rcClient.top);
Graphics grph(pDC->m_hDC);
grph.DrawImage(&bmp, 0, 0);
}
</code></pre>
<p>Am I doing something wrong? Or is there another way to achieve this?</p>
|
[
{
"answer_id": 198068,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "<p>You might try using old-fashioned GDI rather than GDI+ to write to the DC, especially since you're already buffering the image. Use Bitmap::LockBits to access the raw bitmap data, create a BITMAPINFO structure, and use SetDIBitsToDevice to display the bitmap.</p>\n"
},
{
"answer_id": 198085,
"author": "Chris Becke",
"author_id": 27491,
"author_profile": "https://Stackoverflow.com/users/27491",
"pm_score": 0,
"selected": false,
"text": "<p>Are there child windows on the form? The Window manager starts by getting the parent window to erase its background by sending a WM_ERASEBKGND message, THEN it sends a wM_PAINT message - presumably this maps to your wx::OnDraw method. Then it iterates over each child control and gets those to paint themselves. </p>\n\n<p>If this is your scenario... using Vistas new aero look would solve your problem as the aero desktop window manager does window compositing automatically. With the older window manager its a pita.</p>\n"
},
{
"answer_id": 198187,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure that the window class for the window does not include the CS_VREDRAW and CS_HREDRAW flags in its style.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/ms633574(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms633574(VS.85).aspx</a></p>\n"
},
{
"answer_id": 199526,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 6,
"selected": true,
"text": "<p>To completely avoid flicker, you would need to complete <em>all</em> drawing in the interval between screen updates. Windows does not provide any easy means of accomplishing this for normal window painting (Vista provides composite drawing via the <a href=\"https://en.wikipedia.org/wiki/Desktop_Window_Manager\" rel=\"noreferrer\">DWM</a>, but this cannot be relied on even on systems running Vista). Therefore, the best you can do to minimize flicker is to draw everything as quickly as possible (<em>reduce</em> tearing by increasing your chances of completing all drawing within a refresh cycle), and avoid overdraw (drawing part of the screen and then drawing something else over the top: risks presenting user with a partially-drawn screen).</p>\n<p>Let's discuss the techniques presented here so far:</p>\n<ul>\n<li><p><strong>Do-nothing <i>OnEraseBkgnd()</i></strong>: helps to avoid over-draw by preventing the invalidated area of the window from being filled with the window's background color. Useful when you will be drawing the entire area again during <i>WM_PAINT</i> handling <em>anyway</em>, as in the case of double-buffered drawing... but see <i>Notes on avoiding overdraw by preventing drawing after your </i>WM_PAINT<i> method</i>.</p>\n</li>\n<li><p><strong>Returning NULL for <i>OnCtlColor()</i></strong>: this shouldn't actually do <em>anything</em>... unless you have child controls on your form. In that case, see <i>Notes on avoiding overdraw by preventing drawing after your </i>WM_PAINT<i> method</i> instead.</p>\n</li>\n<li><p><strong>Double buffered drawing</strong>: helps to avoid tearing (and potentially overdraw as well), by reducing the actual on-screen drawing to a single <a href=\"https://en.wikipedia.org/wiki/Bit_blit\" rel=\"noreferrer\">BitBLT</a>. May hurt the time needed for drawing though: hardware acceleration cannot be used (although with GDI+, the chances of any hardware-assisted drawing being used are quite slim), an off-screen bitmap must be created and filled for each redraw, and the entire window must be repainted for each redraw. See <em>Notes on efficient double-buffering</em>.</p>\n</li>\n<li><p><strong>Using GDI calls rather than GDI+ for the BitBlt</strong>: This is often a good idea - <code>Graphics::DrawImage()</code> can be very slow. I've even found the normal GDI <a href=\"https://msdn.microsoft.com/en-us/library/dd183370.aspx\" rel=\"noreferrer\"><code>BitBlt()</code></a> call to be faster on some systems. Play around with this, but only after trying a few other suggestions first.</p>\n</li>\n<li><p><strong>Avoiding window class styles that force a full redraw on each resize (<i>CS_VREDRAW</i>, <i>CS_HREDRAW</i>)</strong>: This will help, but only if you don't <em>need</em> to redraw the entire window when size changes.</p>\n</li>\n</ul>\n<h3>Notes on avoiding overdraw by preventing drawing prior to your <i>WM_PAINT</i> method</h3>\n<p>When all or a portion of a window is invalidated, it will be erased and repainted. As already noted, you can skip erasing if you plan to repaint the entire invalid area. <strong>However</strong>, if you are working with a child window, then you must ensure that parent window(s) are not also erasing your area of the screen. The <i>WS_CLIPCHILDREN</i> style should be set on all parent windows - this will prevent the areas occupied by child windows (including your view) from being drawn on.</p>\n<h3>Notes on avoiding overdraw by preventing drawing after your <i>WM_PAINT</i> method</h3>\n<p>If you have <em>any</em> child controls hosted on your form, you will want to use the <i>WS_CLIPCHILDREN</i> style to avoid drawing over them (and subsequently being over drawn by them. Be aware, this will impact the speed of the BitBlt routine somewhat.</p>\n<h3>Notes on efficient double-buffering</h3>\n<p>Right now, you're creating a new back-buffer image each time the view draws itself. For larger windows, this can represent a significant amount of memory being allocated and released, and <em>will</em> result in significant performance problems. I recommend keeping a dynamically-allocated bitmap in your view object, re-allocating it as needed to match the size of your view.</p>\n<p>Note that while the window is being resized, this will result in just as many allocations as the present system, since each new size will require a new back buffer bitmap to be allocated to match it - you can ease the pain somewhat by rounding dimensions up to the next largest multiple of 4, 8, 16, etc., allowing you to avoid re-allocated on each tiny change in size.</p>\n<p>Note that, if the size of the window hasn't changed since the last time you rendered into the back buffer, you don't need to re-render it when the window is invalidated - just Blt out the already-rendered image onto the screen.</p>\n<p>Also, allocate a bitmap that matches the bit depth of the screen. The constructor for <code>Bitmap</code> you're currently using will default to 32bpp, ARGB-layout; if this doesn't match the screen, then it will have to be converted. Consider using the GDI method <a href=\"https://msdn.microsoft.com/en-us/library/dd183488.aspx\" rel=\"noreferrer\"><code>CreateCompatibleBitmap()</code></a> to get a matching bitmap.</p>\n<p>Finally... I assume your example code is just that, an illustrative snippet. But, if you are actually doing nothing beyond rendering an existing image onto the screen, then you don't really need to maintain a back buffer at all - just Blt directly from the image (and convert the format of the image ahead of time to match the screen).</p>\n"
},
{
"answer_id": 10518317,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 2,
"selected": false,
"text": "<p>You may get some traction through using <a href=\"http://en.wikipedia.org/wiki/Microsoft_Direct3D\" rel=\"nofollow\">Direct3D</a> to \"tell\" you when vsync's occur, et al, so you can BitBlt/update at a good time. See <em><a href=\"http://betterlogic.com/roger/2012/05/gdi-vsync-to-avoid-tearing/\" rel=\"nofollow\">GDI vsync to avoid tearing</a></em> (though getting things down to a single small BitBlt may be \"good enough\" for some cases).</p>\n\n<p>Also note that it appears that GDI BitBlt isn't synchronized with screen vsync. See <em><a href=\"http://www.itlisting.org/4-windows-ce-embedded/7752b5a1dabede5f.aspx\" rel=\"nofollow\">\nFaster than BitBlt</a></em>. </p>\n\n<p>Also note that using CAPTUREBLT (which allows you to capture transparent windows) causes the mouse to flicker (if aero is not in use) if used.</p>\n"
},
{
"answer_id": 18530063,
"author": "Liam",
"author_id": 460851,
"author_profile": "https://Stackoverflow.com/users/460851",
"pm_score": 2,
"selected": false,
"text": "<p>This link contains some useful info:\n<a href=\"http://www.catch22.net/tuts/flicker-free-drawing\" rel=\"nofollow\">http://www.catch22.net/tuts/flicker-free-drawing</a></p>\n\n<p>(I know this is a very late addition to the thread, but this is for anyone (like me) who found it when looking to reduce flicker in my Win32 app...)</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4880/"
] |
I'm using GDI+ in a C++/MFC application and I just can't seem to avoid flickering whenever the window is resized.
I have already tried these steps:
* returned TRUE on `OnEraseBkGnd()`;
* returned NULL on `OnCtlColor()`;
* used double buffering according to this code:
```
void vwView::OnDraw(CDC* pDC)
{
CRect rcClient;
GetClientRect(rcClient);
Bitmap bmp(rcClient.Width(), rcClient.Height());
Graphics graphics(&bmp);
graphics.DrawImage(m_image, rcClient.left, rcClient.top);
Graphics grph(pDC->m_hDC);
grph.DrawImage(&bmp, 0, 0);
}
```
Am I doing something wrong? Or is there another way to achieve this?
|
To completely avoid flicker, you would need to complete *all* drawing in the interval between screen updates. Windows does not provide any easy means of accomplishing this for normal window painting (Vista provides composite drawing via the [DWM](https://en.wikipedia.org/wiki/Desktop_Window_Manager), but this cannot be relied on even on systems running Vista). Therefore, the best you can do to minimize flicker is to draw everything as quickly as possible (*reduce* tearing by increasing your chances of completing all drawing within a refresh cycle), and avoid overdraw (drawing part of the screen and then drawing something else over the top: risks presenting user with a partially-drawn screen).
Let's discuss the techniques presented here so far:
* **Do-nothing *OnEraseBkgnd()***: helps to avoid over-draw by preventing the invalidated area of the window from being filled with the window's background color. Useful when you will be drawing the entire area again during *WM\_PAINT* handling *anyway*, as in the case of double-buffered drawing... but see *Notes on avoiding overdraw by preventing drawing after your* WM\_PAINT *method*.
* **Returning NULL for *OnCtlColor()***: this shouldn't actually do *anything*... unless you have child controls on your form. In that case, see *Notes on avoiding overdraw by preventing drawing after your* WM\_PAINT *method* instead.
* **Double buffered drawing**: helps to avoid tearing (and potentially overdraw as well), by reducing the actual on-screen drawing to a single [BitBLT](https://en.wikipedia.org/wiki/Bit_blit). May hurt the time needed for drawing though: hardware acceleration cannot be used (although with GDI+, the chances of any hardware-assisted drawing being used are quite slim), an off-screen bitmap must be created and filled for each redraw, and the entire window must be repainted for each redraw. See *Notes on efficient double-buffering*.
* **Using GDI calls rather than GDI+ for the BitBlt**: This is often a good idea - `Graphics::DrawImage()` can be very slow. I've even found the normal GDI [`BitBlt()`](https://msdn.microsoft.com/en-us/library/dd183370.aspx) call to be faster on some systems. Play around with this, but only after trying a few other suggestions first.
* **Avoiding window class styles that force a full redraw on each resize (*CS\_VREDRAW*, *CS\_HREDRAW*)**: This will help, but only if you don't *need* to redraw the entire window when size changes.
### Notes on avoiding overdraw by preventing drawing prior to your *WM\_PAINT* method
When all or a portion of a window is invalidated, it will be erased and repainted. As already noted, you can skip erasing if you plan to repaint the entire invalid area. **However**, if you are working with a child window, then you must ensure that parent window(s) are not also erasing your area of the screen. The *WS\_CLIPCHILDREN* style should be set on all parent windows - this will prevent the areas occupied by child windows (including your view) from being drawn on.
### Notes on avoiding overdraw by preventing drawing after your *WM\_PAINT* method
If you have *any* child controls hosted on your form, you will want to use the *WS\_CLIPCHILDREN* style to avoid drawing over them (and subsequently being over drawn by them. Be aware, this will impact the speed of the BitBlt routine somewhat.
### Notes on efficient double-buffering
Right now, you're creating a new back-buffer image each time the view draws itself. For larger windows, this can represent a significant amount of memory being allocated and released, and *will* result in significant performance problems. I recommend keeping a dynamically-allocated bitmap in your view object, re-allocating it as needed to match the size of your view.
Note that while the window is being resized, this will result in just as many allocations as the present system, since each new size will require a new back buffer bitmap to be allocated to match it - you can ease the pain somewhat by rounding dimensions up to the next largest multiple of 4, 8, 16, etc., allowing you to avoid re-allocated on each tiny change in size.
Note that, if the size of the window hasn't changed since the last time you rendered into the back buffer, you don't need to re-render it when the window is invalidated - just Blt out the already-rendered image onto the screen.
Also, allocate a bitmap that matches the bit depth of the screen. The constructor for `Bitmap` you're currently using will default to 32bpp, ARGB-layout; if this doesn't match the screen, then it will have to be converted. Consider using the GDI method [`CreateCompatibleBitmap()`](https://msdn.microsoft.com/en-us/library/dd183488.aspx) to get a matching bitmap.
Finally... I assume your example code is just that, an illustrative snippet. But, if you are actually doing nothing beyond rendering an existing image onto the screen, then you don't really need to maintain a back buffer at all - just Blt directly from the image (and convert the format of the image ahead of time to match the screen).
|
197,951 |
<p>I have a need to work with Windows executables which are made for x86, x64, and IA64. I'd like to programmatically figure out the platform by examining the files themselves.</p>
<p>My target language is PowerShell but a C# example will do. Failing either of those, if you know the logic required that would be great.</p>
|
[
{
"answer_id": 197974,
"author": "Sec",
"author_id": 20555,
"author_profile": "https://Stackoverflow.com/users/20555",
"pm_score": 0,
"selected": false,
"text": "<p>Unix OS have a utility called \"file\" which identifies files. The rules for identifying are kept in a description file called \"magic\". You could try file to see if it is able to identify your files correctly and grab the appropriate rules out of the magic file.</p>\n"
},
{
"answer_id": 198005,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Assembly assembly = Assembly.LoadFile(Path.GetFullPath(\"ConsoleApplication1.exe\"));\nModule manifestModule = assembly.ManifestModule;\nPortableExecutableKinds peKind;\nImageFileMachine machine;\nmanifestModule.GetPEKind(out peKind, out machine);\n</code></pre>\n\n<p>The target machine should then be in machine.</p>\n\n<p>That'll only work with .NET assemblies though.</p>\n"
},
{
"answer_id": 198009,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 4,
"selected": false,
"text": "<p>You need the GetBinaryType win32 function. This will return the relevant parts of the PE-format executable.</p>\n\n<p>Typically, you'll get either SCS_32BIT_BINARY or SCS_64BIT_BINARY in the BinaryType field, </p>\n\n<p>Alternativaly you can check the PE format itself to see what architecture the executable is compiled for.</p>\n\n<p>The IMAGE_FILE_HEADER.Machine field will have \"IMAGE_FILE_MACHINE_IA64\" set for IA64 binaries, IMAGE_FILE_MACHINE_I386 for 32-bit and IMAGE_FILE_MACHINE_AMD64 for 64-bit (ie x86_64).</p>\n\n<p>There's a <a href=\"http://msdn.microsoft.com/en-gb/magazine/cc301805.aspx\" rel=\"noreferrer\">MSDN magazine article</a> to help you get going.</p>\n\n<p>Addendum: <a href=\"http://webster.cs.ucr.edu/Page_TechDocs/pe.txt\" rel=\"noreferrer\">This</a> may help you a little more. You read the binary as a file: check the first 2 bytes say \"MZ\", then skip the next 58 bytes and read the magic 32-bit value at 60 bytes into the image (which equals 0x00004550 for PE executables). The following bytes are <a href=\"http://msdn.microsoft.com/en-us/library/ms680313(VS.85).aspx\" rel=\"noreferrer\">this header</a>, the first 2 bytes of which tell you which machine the binary is designed for (0x8664 = x86_64, 0x0200 = IA64, 0x014c = i386).</p>\n\n<p>(executive summary: read bytes 65 and 66 of the file to get the image type)</p>\n"
},
{
"answer_id": 198201,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 1,
"selected": false,
"text": "<p>I can offer a <a href=\"http://blogs.msdn.com/kstanton/archive/2004/03/31/105060.aspx\" rel=\"nofollow noreferrer\">link to some C# code</a> for accessing the IMAGE_FILE_HEADER, which I think could be (easily) compiled into a PowerShell cmdlet. I'm reasonably sure you can't use that method in PowerShell script directly, since it lacks pointers and PInvoke capability.</p>\n\n<p>However, you should be able to use your by now extensive knowledge of the PE header format ;-) to just go \"straight\" to the right bytes and figure it out. This <em>will</em> work in PowerShell script, and you should be able to just convert <a href=\"http://anastasiosyal.com/archive/2007/04/17/3.aspx\" rel=\"nofollow noreferrer\">this C# code from Tasos' blog</a> to script. I won't bother repeating the code here since it's not mine.</p>\n"
},
{
"answer_id": 885481,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 6,
"selected": true,
"text": "<p>(from another Q, since removed)</p>\n\n<p>Machine type: This is a quick little bit of code I based on some that gets the linker timestamp. This is in the same header, and it seems to work - it returns I386 when compiled -any cpu-, and x64 when compiled with that as the target platform.</p>\n\n<p>The Exploring PE Headers (K. Stanton,MSDN) blog entry that showed me the offset, as another response noted.</p>\n\n<pre><code>public enum MachineType {\n Native = 0, I386 = 0x014c, Itanium = 0x0200, x64 = 0x8664\n}\n\npublic static MachineType GetMachineType(string fileName)\n{\n const int PE_POINTER_OFFSET = 60; \n const int MACHINE_OFFSET = 4;\n byte[] data = new byte[4096];\n using (Stream s = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {\n s.Read(data, 0, 4096);\n }\n // dos header is 64 bytes, last element, long (4 bytes) is the address of the PE header\n int PE_HEADER_ADDR = BitConverter.ToInt32(data, PE_POINTER_OFFSET);\n int machineUint = BitConverter.ToUInt16(data, PE_HEADER_ADDR + MACHINE_OFFSET);\n return (MachineType)machineUint;\n}\n</code></pre>\n"
},
{
"answer_id": 4719567,
"author": "Keith Hill",
"author_id": 153982,
"author_profile": "https://Stackoverflow.com/users/153982",
"pm_score": 5,
"selected": false,
"text": "<p>If you have Visual Studio installed you can use <code>dumpbin.exe</code>. There's also the <code>Get-PEHeader</code> cmdlet in the <a href=\"http://pscx.codeplex.com\" rel=\"noreferrer\">PowerShell Community Extensions</a> that can be used to test for executable images.</p>\n\n<p>Dumpbin will report DLLs as <code>machine (x86)</code> or <code>machine (x64)</code></p>\n\n<p>Get-PEHeader will report DLLs as either <code>PE32</code> or <code>PE32+</code></p>\n"
},
{
"answer_id": 38806690,
"author": "Kraang Prime",
"author_id": 3504007,
"author_profile": "https://Stackoverflow.com/users/3504007",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my own implementation of this which has several more checks in place and always returns a result.</p>\n\n<pre><code>// the enum of known pe file types\npublic enum FilePEType : ushort\n{\n IMAGE_FILE_MACHINE_UNKNOWN = 0x0,\n IMAGE_FILE_MACHINE_AM33 = 0x1d3,\n IMAGE_FILE_MACHINE_AMD64 = 0x8664,\n IMAGE_FILE_MACHINE_ARM = 0x1c0,\n IMAGE_FILE_MACHINE_EBC = 0xebc,\n IMAGE_FILE_MACHINE_I386 = 0x14c,\n IMAGE_FILE_MACHINE_IA64 = 0x200,\n IMAGE_FILE_MACHINE_M32R = 0x9041,\n IMAGE_FILE_MACHINE_MIPS16 = 0x266,\n IMAGE_FILE_MACHINE_MIPSFPU = 0x366,\n IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,\n IMAGE_FILE_MACHINE_POWERPC = 0x1f0,\n IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,\n IMAGE_FILE_MACHINE_R4000 = 0x166,\n IMAGE_FILE_MACHINE_SH3 = 0x1a2,\n IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,\n IMAGE_FILE_MACHINE_SH4 = 0x1a6,\n IMAGE_FILE_MACHINE_SH5 = 0x1a8,\n IMAGE_FILE_MACHINE_THUMB = 0x1c2,\n IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,\n}\n\n// pass the path to the file and check the return\npublic static FilePEType GetFilePE(string path)\n{\n FilePEType pe = new FilePEType();\n pe = FilePEType.IMAGE_FILE_MACHINE_UNKNOWN;\n if(File.Exists(path))\n {\n using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n {\n byte[] data = new byte[4096];\n fs.Read(data, 0, 4096);\n ushort result = BitConverter.ToUInt16(data, BitConverter.ToInt32(data, 60) + 4);\n try\n {\n pe = (FilePEType)result;\n } catch (Exception)\n {\n pe = FilePEType.IMAGE_FILE_MACHINE_UNKNOWN;\n }\n }\n }\n return pe;\n}\n</code></pre>\n\n<p>How to use :</p>\n\n<pre><code>string myfile = @\"c:\\windows\\explorer.exe\"; // the file\nFilePEType pe = GetFilePE( myfile );\n\nSystem.Diagnostics.WriteLine( pe.ToString() );\n</code></pre>\n\n<p>For the enum values used here, they were obtained from <a href=\"https://golang.org/src/debug/pe/pe.go\" rel=\"nofollow\">pe.go</a> . The reason why this works is that for each binary ditribution of 'go' must have the correct flag in the assembly to let it pass the operating systems 'can you run here ?' check. Since 'go' is cross platform (all platforms), it is a good base to get this information. There are probably other sources for this information, but they seem to be nested knee-deep in google ca-ca requiring a 10th dan black-belt in Google-fu to locate. </p>\n"
},
{
"answer_id": 49110144,
"author": "default",
"author_id": 1069238,
"author_profile": "https://Stackoverflow.com/users/1069238",
"pm_score": 3,
"selected": false,
"text": "<p>According to <a href=\"https://www.raymond.cc/blog/determine-application-compiled-32-64-bit/\" rel=\"nofollow noreferrer\">"10 Ways to Determine if Application is Compiled for 32-bit or 64-bit"</a>, you can check if a DLL or EXE is 32-bit or 64-bit by opening it with <strong>Notepad</strong> and looking for <code>PE</code> at the beginning - if the 3rd letter after that is:</p>\n<ul>\n<li>an <code>L</code> the platform is 32-bit:\n<img src=\"https://img.raymond.cc/blog/wp-content/uploads/2015/11/notepad-32bit.png\" alt=\"Notepad with x32 binary\" /></li>\n<li>a <code>d</code> the platform is 64-bit:\n<img src=\"https://img.raymond.cc/blog/wp-content/uploads/2015/11/notepad-64bit.png\" alt=\"Notepad with x64 binary\" /></li>\n</ul>\n<p>I tried it on my DLLs and it seems to be accurate.</p>\n"
},
{
"answer_id": 50471830,
"author": "Jiminion",
"author_id": 2587816,
"author_profile": "https://Stackoverflow.com/users/2587816",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an implementation in C.</p>\n\n<pre><code>// Determines if DLL is 32-bit or 64-bit.\n#include <stdio.h>\n\nint sGetDllType(const char *dll_name);\n\nint main()\n{\n int ret;\n const char *fname = \"sample_32.dll\";\n //const char *fname = \"sample_64.dll\";\n ret = sGetDllType(fname);\n}\n\nstatic int sGetDllType(const char *dll_name) {\n const int PE_POINTER_OFFSET = 60;\n const int MACHINE_TYPE_OFFSET = 4;\n FILE *fp;\n unsigned int ret = 0;\n int peoffset;\n unsigned short machine;\n\n fp = fopen(dll_name, \"rb\");\n unsigned char data[4096];\n ret = fread(data, sizeof(char), 4096, fp);\n fclose(fp);\n if (ret == 0)\n return -1;\n\n if ( (data[0] == 'M') && (data[1] == 'Z') ) {\n // Initial magic header is good\n peoffset = data[PE_POINTER_OFFSET + 3];\n peoffset = (peoffset << 8) + data[PE_POINTER_OFFSET + 2];\n peoffset = (peoffset << 8) + data[PE_POINTER_OFFSET + 1];\n peoffset = (peoffset << 8) + data[PE_POINTER_OFFSET];\n\n // Check second header\n if ((data[peoffset] == 'P') && (data[peoffset + 1] == 'E')) {\n machine = data[peoffset + MACHINE_TYPE_OFFSET];\n machine = (machine)+(data[peoffset + MACHINE_TYPE_OFFSET + 1] << 8);\n\n if (machine == 0x014c)\n return 32;\n if (machine == 0x8664)\n return 64;\n\n return -1;\n }\n return -1;\n }\n else\n return -1;\n}\n</code></pre>\n"
},
{
"answer_id": 51278133,
"author": "Saad Saadi",
"author_id": 1111249,
"author_profile": "https://Stackoverflow.com/users/1111249",
"pm_score": 2,
"selected": false,
"text": "<p><code>dumpbin.exe</code> available under <code>bin</code> directory of Visual Studio works for both <code>.lib</code> and <code>.dll</code> </p>\n\n<pre><code> dumpbin.exe /headers *.dll |findstr machine\n dumpbin.exe /headers *.lib |findstr machine\n</code></pre>\n"
},
{
"answer_id": 66548864,
"author": "John Matthews",
"author_id": 8771014,
"author_profile": "https://Stackoverflow.com/users/8771014",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a C++ MFC console application that writes out the file header information. You can check the machine type (IMAGE_FILE_HEADER Machine member) or the IMAGE_FILE_32BIT_MACHINE flag in the Characteristics to see what platform the file is built for. See WinNT.h for more info on the structures.</p>\n<pre><code>#include "stdafx.h"\n\nint _tmain(int argc, TCHAR* argv[], TCHAR* envp[])\n{\n int nRetCode = 0;\n int nrd;\n\n IMAGE_DOS_HEADER idh;\n IMAGE_NT_HEADERS inth;\n IMAGE_FILE_HEADER ifh;\n\n // initialize MFC and print and error on failure\n if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))\n {\n _tprintf(_T("Fatal Error: MFC initialization failed\\n"));\n nRetCode = 1;\n return 1;\n }\n if (argc != 2) {\n _ftprintf(stderr, _T("Usage: %s filename\\n"), argv[0]);\n return 1;\n }\n // Try to open the file\n CFile ckf;\n CFileException ex;\n DWORD flags = CFile::modeRead | CFile::shareDenyNone;\n\n if (!ckf.Open(argv[1], flags, &ex)) {\n TCHAR szError[1024];\n ex.GetErrorMessage(szError, 1024);\n _tprintf_s(_T("Couldn't open file: %1024s"), szError);\n return 2;\n }\n\n // The following is adapted from:\n // https://stackoverflow.com/questions/495244/how-can-i-test-a-windows-dll-file-to-determine-if-it-is-32-bit-or-64-bit\n // https://stackoverflow.com/questions/46024914/how-to-parse-exe-file-and-get-data-from-image-dos-header-structure-using-c-and\n // Seek to beginning of file\n ckf.Seek(0, CFile::begin);\n\n // Read DOS header\n int nbytes = sizeof(IMAGE_DOS_HEADER);\n nrd = ckf.Read(&idh, nbytes);\n\n // The idh.e_lfanew member is the offset to the NT_HEADERS structure\n ckf.Seek(idh.e_lfanew, CFile::begin);\n\n // Read NT headers\n nbytes = sizeof(IMAGE_NT_HEADERS);\n nrd = ckf.Read(&inth, nbytes);\n\n ifh = inth.FileHeader;\n\n _ftprintf(stdout, _T("File machine type: "));\n switch (ifh.Machine) {\n case IMAGE_FILE_MACHINE_I386:\n _ftprintf(stdout, _T("I386\\n"));\n break;\n case IMAGE_FILE_MACHINE_IA64:\n _ftprintf(stdout, _T("IA64\\n"));\n break;\n case IMAGE_FILE_MACHINE_AMD64:\n _ftprintf(stdout, _T("AMD64\\n"));\n break;\n default:\n _ftprintf(stdout, _T("Unknown (%d = %X)\\n"), ifh.Machine, ifh.Machine);\n break;\n }\n\n // Write characteristics (see WinNT.h)\n _ftprintf(stdout, _T("Characteristics:\\n"));\n _ftprintf(stdout, _T("RELOCS_STRIPPED Relocation info stripped from file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("EXECUTABLE_IMAGE File is executable (i.e. no unresolved externel references): %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("LINE_NUMS_STRIPPED Line nunbers stripped from file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_LINE_NUMS_STRIPPED ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("LOCAL_SYMS_STRIPPED Local symbols stripped from file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_LOCAL_SYMS_STRIPPED ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("AGGRESIVE_WS_TRIM Agressively trim working set: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_AGGRESIVE_WS_TRIM ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("LARGE_ADDRESS_AWARE App can handle >2gb addresses: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("BYTES_REVERSED_LO Bytes of machine word are reversed: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_BYTES_REVERSED_LO ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("32BIT_MACHINE 32 bit word machine: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_32BIT_MACHINE ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("DEBUG_STRIPPED Debugging info stripped from file in .DBG file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_DEBUG_STRIPPED ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("REMOVABLE_RUN_FROM_SWAP If Image is on removable media, copy and run from the swap file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("NET_RUN_FROM_SWAP If Image is on Net, copy and run from the swap file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_NET_RUN_FROM_SWAP ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("SYSTEM System File: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_SYSTEM ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("DLL File is a DLL: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_DLL ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("UP_SYSTEM_ONLY File should only be run on a UP machine: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_UP_SYSTEM_ONLY ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("BYTES_REVERSED_HI Bytes of machine word are reversed: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_BYTES_REVERSED_HI ? _T('Y') : _T('N')));\n\n\n ckf.Close();\n\n return nRetCode;\n}\n</code></pre>\n"
},
{
"answer_id": 67739487,
"author": "risingballs",
"author_id": 1177068,
"author_profile": "https://Stackoverflow.com/users/1177068",
"pm_score": 0,
"selected": false,
"text": "<p>Here's another solution using C/C++ as a standalone tool, ready to be adapted to whatever you need:</p>\n<pre><code>// Fri May 28, 2021 -two\n\n#include <stdio.h>\n#include <io.h>\n#include <stdint.h>\n#include <iostream.h>\nusing namespace std;\n\nbool queryExeMachineType( const char *filename )\n{\n FILE *fp = fopen( filename, "rb" );\n\n if (fp == NULL)\n return false;\n\n // DOS header is 64 bytes\n const uint32_t fsize = filelength( fileno( fp ) );\n char magic[ 2 ] = { 0 };\n uint32_t offset = 0;\n uint16_t machine = 0;\n\n if (fread( magic, 1, 2, fp ) != 2 || magic[ 0 ] != 'M' || magic[ 1 ] != 'Z')\n {\n cerr << "not an executable file" << endl;\n fclose( fp );\n return false;\n }\n fseek( fp, 60, SEEK_SET );\n fread( &offset, 1, 4, fp );\n\n if (offset >= fsize)\n {\n cerr << "invalid pe offset" << endl;\n fclose( fp );\n return false;\n }\n fseek( fp, offset, SEEK_SET );\n\n if (fread( magic, 1, 2, fp ) != 2 || magic[ 0 ] != 'P' || magic[ 1 ] != 'E')\n {\n cerr << "not a pe executable" << endl;\n fclose( fp );\n return false;\n }\n fread( magic, 1, 2, fp );\n fread( &machine, 1, 2, fp );\n\n switch (machine)\n {\n case 0x014c:\n cout << "i386" << endl; // x86\n break;\n\n case 0x8664:\n cout << "amd64" << endl; // x86_64\n break;\n\n case 0x0200:\n cout << "ia64" << endl; // itanium\n break;\n\n default:\n cerr << "unknown machine 0x" << hex << machine << endl;\n break;\n }\n fclose( fp );\n return true;\n}\n\nint main( int argc, char *argv[] )\n{\n const char *fn = (argc > 1) ? argv[ 1 ] : "test.dll";\n\n if (queryExeMachineType( fn ))\n cerr << "succeeded" << endl;\n else\n cerr << "failed" << endl;\n\n return 0;\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6637/"
] |
I have a need to work with Windows executables which are made for x86, x64, and IA64. I'd like to programmatically figure out the platform by examining the files themselves.
My target language is PowerShell but a C# example will do. Failing either of those, if you know the logic required that would be great.
|
(from another Q, since removed)
Machine type: This is a quick little bit of code I based on some that gets the linker timestamp. This is in the same header, and it seems to work - it returns I386 when compiled -any cpu-, and x64 when compiled with that as the target platform.
The Exploring PE Headers (K. Stanton,MSDN) blog entry that showed me the offset, as another response noted.
```
public enum MachineType {
Native = 0, I386 = 0x014c, Itanium = 0x0200, x64 = 0x8664
}
public static MachineType GetMachineType(string fileName)
{
const int PE_POINTER_OFFSET = 60;
const int MACHINE_OFFSET = 4;
byte[] data = new byte[4096];
using (Stream s = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
s.Read(data, 0, 4096);
}
// dos header is 64 bytes, last element, long (4 bytes) is the address of the PE header
int PE_HEADER_ADDR = BitConverter.ToInt32(data, PE_POINTER_OFFSET);
int machineUint = BitConverter.ToUInt16(data, PE_HEADER_ADDR + MACHINE_OFFSET);
return (MachineType)machineUint;
}
```
|
197,957 |
<p>Hoi!</p>
<p>I have a form I wish to submit, but I need to add the PHPSESSID, because some clients allow no cookies.</p>
<p>There are several javascript functions on my page which displays a list of users (search, sort, open details), the page is generated by PHP.</p>
<p>Now I am looking for an elegant way to have the PHPSESSID included in every submit of my form - this needs to be done on several pages, so I hope for an easy solution. Adding the PHPSESSID to the action or into a hidden field does not work properly.</p>
<p>Or is this problem located elsewhere? It could be the client is behind a too restrictive firewall or something. Any ideas (especially with solutions ;-) ) in that direction are also welcome!</p>
<p>Example code (extremely simplified):</p>
<pre><code><form name="userlist" method="POST" action="./myuserlist.php">
[...some formfields and stuff..]
</form>
<script>
//one example function, there are several on my page
function next_page()
{
//set some hidden field to get the next page
document.forms[0].submit();
}
</script>
</code></pre>
<p>Thanks in advance!</p>
<p>Bye,
Basty</p>
<p><strong>[EDIT]</strong>
session.use_trans_sid is set to true</p>
|
[
{
"answer_id": 197974,
"author": "Sec",
"author_id": 20555,
"author_profile": "https://Stackoverflow.com/users/20555",
"pm_score": 0,
"selected": false,
"text": "<p>Unix OS have a utility called \"file\" which identifies files. The rules for identifying are kept in a description file called \"magic\". You could try file to see if it is able to identify your files correctly and grab the appropriate rules out of the magic file.</p>\n"
},
{
"answer_id": 198005,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Assembly assembly = Assembly.LoadFile(Path.GetFullPath(\"ConsoleApplication1.exe\"));\nModule manifestModule = assembly.ManifestModule;\nPortableExecutableKinds peKind;\nImageFileMachine machine;\nmanifestModule.GetPEKind(out peKind, out machine);\n</code></pre>\n\n<p>The target machine should then be in machine.</p>\n\n<p>That'll only work with .NET assemblies though.</p>\n"
},
{
"answer_id": 198009,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 4,
"selected": false,
"text": "<p>You need the GetBinaryType win32 function. This will return the relevant parts of the PE-format executable.</p>\n\n<p>Typically, you'll get either SCS_32BIT_BINARY or SCS_64BIT_BINARY in the BinaryType field, </p>\n\n<p>Alternativaly you can check the PE format itself to see what architecture the executable is compiled for.</p>\n\n<p>The IMAGE_FILE_HEADER.Machine field will have \"IMAGE_FILE_MACHINE_IA64\" set for IA64 binaries, IMAGE_FILE_MACHINE_I386 for 32-bit and IMAGE_FILE_MACHINE_AMD64 for 64-bit (ie x86_64).</p>\n\n<p>There's a <a href=\"http://msdn.microsoft.com/en-gb/magazine/cc301805.aspx\" rel=\"noreferrer\">MSDN magazine article</a> to help you get going.</p>\n\n<p>Addendum: <a href=\"http://webster.cs.ucr.edu/Page_TechDocs/pe.txt\" rel=\"noreferrer\">This</a> may help you a little more. You read the binary as a file: check the first 2 bytes say \"MZ\", then skip the next 58 bytes and read the magic 32-bit value at 60 bytes into the image (which equals 0x00004550 for PE executables). The following bytes are <a href=\"http://msdn.microsoft.com/en-us/library/ms680313(VS.85).aspx\" rel=\"noreferrer\">this header</a>, the first 2 bytes of which tell you which machine the binary is designed for (0x8664 = x86_64, 0x0200 = IA64, 0x014c = i386).</p>\n\n<p>(executive summary: read bytes 65 and 66 of the file to get the image type)</p>\n"
},
{
"answer_id": 198201,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 1,
"selected": false,
"text": "<p>I can offer a <a href=\"http://blogs.msdn.com/kstanton/archive/2004/03/31/105060.aspx\" rel=\"nofollow noreferrer\">link to some C# code</a> for accessing the IMAGE_FILE_HEADER, which I think could be (easily) compiled into a PowerShell cmdlet. I'm reasonably sure you can't use that method in PowerShell script directly, since it lacks pointers and PInvoke capability.</p>\n\n<p>However, you should be able to use your by now extensive knowledge of the PE header format ;-) to just go \"straight\" to the right bytes and figure it out. This <em>will</em> work in PowerShell script, and you should be able to just convert <a href=\"http://anastasiosyal.com/archive/2007/04/17/3.aspx\" rel=\"nofollow noreferrer\">this C# code from Tasos' blog</a> to script. I won't bother repeating the code here since it's not mine.</p>\n"
},
{
"answer_id": 885481,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 6,
"selected": true,
"text": "<p>(from another Q, since removed)</p>\n\n<p>Machine type: This is a quick little bit of code I based on some that gets the linker timestamp. This is in the same header, and it seems to work - it returns I386 when compiled -any cpu-, and x64 when compiled with that as the target platform.</p>\n\n<p>The Exploring PE Headers (K. Stanton,MSDN) blog entry that showed me the offset, as another response noted.</p>\n\n<pre><code>public enum MachineType {\n Native = 0, I386 = 0x014c, Itanium = 0x0200, x64 = 0x8664\n}\n\npublic static MachineType GetMachineType(string fileName)\n{\n const int PE_POINTER_OFFSET = 60; \n const int MACHINE_OFFSET = 4;\n byte[] data = new byte[4096];\n using (Stream s = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {\n s.Read(data, 0, 4096);\n }\n // dos header is 64 bytes, last element, long (4 bytes) is the address of the PE header\n int PE_HEADER_ADDR = BitConverter.ToInt32(data, PE_POINTER_OFFSET);\n int machineUint = BitConverter.ToUInt16(data, PE_HEADER_ADDR + MACHINE_OFFSET);\n return (MachineType)machineUint;\n}\n</code></pre>\n"
},
{
"answer_id": 4719567,
"author": "Keith Hill",
"author_id": 153982,
"author_profile": "https://Stackoverflow.com/users/153982",
"pm_score": 5,
"selected": false,
"text": "<p>If you have Visual Studio installed you can use <code>dumpbin.exe</code>. There's also the <code>Get-PEHeader</code> cmdlet in the <a href=\"http://pscx.codeplex.com\" rel=\"noreferrer\">PowerShell Community Extensions</a> that can be used to test for executable images.</p>\n\n<p>Dumpbin will report DLLs as <code>machine (x86)</code> or <code>machine (x64)</code></p>\n\n<p>Get-PEHeader will report DLLs as either <code>PE32</code> or <code>PE32+</code></p>\n"
},
{
"answer_id": 38806690,
"author": "Kraang Prime",
"author_id": 3504007,
"author_profile": "https://Stackoverflow.com/users/3504007",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my own implementation of this which has several more checks in place and always returns a result.</p>\n\n<pre><code>// the enum of known pe file types\npublic enum FilePEType : ushort\n{\n IMAGE_FILE_MACHINE_UNKNOWN = 0x0,\n IMAGE_FILE_MACHINE_AM33 = 0x1d3,\n IMAGE_FILE_MACHINE_AMD64 = 0x8664,\n IMAGE_FILE_MACHINE_ARM = 0x1c0,\n IMAGE_FILE_MACHINE_EBC = 0xebc,\n IMAGE_FILE_MACHINE_I386 = 0x14c,\n IMAGE_FILE_MACHINE_IA64 = 0x200,\n IMAGE_FILE_MACHINE_M32R = 0x9041,\n IMAGE_FILE_MACHINE_MIPS16 = 0x266,\n IMAGE_FILE_MACHINE_MIPSFPU = 0x366,\n IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,\n IMAGE_FILE_MACHINE_POWERPC = 0x1f0,\n IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,\n IMAGE_FILE_MACHINE_R4000 = 0x166,\n IMAGE_FILE_MACHINE_SH3 = 0x1a2,\n IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,\n IMAGE_FILE_MACHINE_SH4 = 0x1a6,\n IMAGE_FILE_MACHINE_SH5 = 0x1a8,\n IMAGE_FILE_MACHINE_THUMB = 0x1c2,\n IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,\n}\n\n// pass the path to the file and check the return\npublic static FilePEType GetFilePE(string path)\n{\n FilePEType pe = new FilePEType();\n pe = FilePEType.IMAGE_FILE_MACHINE_UNKNOWN;\n if(File.Exists(path))\n {\n using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n {\n byte[] data = new byte[4096];\n fs.Read(data, 0, 4096);\n ushort result = BitConverter.ToUInt16(data, BitConverter.ToInt32(data, 60) + 4);\n try\n {\n pe = (FilePEType)result;\n } catch (Exception)\n {\n pe = FilePEType.IMAGE_FILE_MACHINE_UNKNOWN;\n }\n }\n }\n return pe;\n}\n</code></pre>\n\n<p>How to use :</p>\n\n<pre><code>string myfile = @\"c:\\windows\\explorer.exe\"; // the file\nFilePEType pe = GetFilePE( myfile );\n\nSystem.Diagnostics.WriteLine( pe.ToString() );\n</code></pre>\n\n<p>For the enum values used here, they were obtained from <a href=\"https://golang.org/src/debug/pe/pe.go\" rel=\"nofollow\">pe.go</a> . The reason why this works is that for each binary ditribution of 'go' must have the correct flag in the assembly to let it pass the operating systems 'can you run here ?' check. Since 'go' is cross platform (all platforms), it is a good base to get this information. There are probably other sources for this information, but they seem to be nested knee-deep in google ca-ca requiring a 10th dan black-belt in Google-fu to locate. </p>\n"
},
{
"answer_id": 49110144,
"author": "default",
"author_id": 1069238,
"author_profile": "https://Stackoverflow.com/users/1069238",
"pm_score": 3,
"selected": false,
"text": "<p>According to <a href=\"https://www.raymond.cc/blog/determine-application-compiled-32-64-bit/\" rel=\"nofollow noreferrer\">"10 Ways to Determine if Application is Compiled for 32-bit or 64-bit"</a>, you can check if a DLL or EXE is 32-bit or 64-bit by opening it with <strong>Notepad</strong> and looking for <code>PE</code> at the beginning - if the 3rd letter after that is:</p>\n<ul>\n<li>an <code>L</code> the platform is 32-bit:\n<img src=\"https://img.raymond.cc/blog/wp-content/uploads/2015/11/notepad-32bit.png\" alt=\"Notepad with x32 binary\" /></li>\n<li>a <code>d</code> the platform is 64-bit:\n<img src=\"https://img.raymond.cc/blog/wp-content/uploads/2015/11/notepad-64bit.png\" alt=\"Notepad with x64 binary\" /></li>\n</ul>\n<p>I tried it on my DLLs and it seems to be accurate.</p>\n"
},
{
"answer_id": 50471830,
"author": "Jiminion",
"author_id": 2587816,
"author_profile": "https://Stackoverflow.com/users/2587816",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an implementation in C.</p>\n\n<pre><code>// Determines if DLL is 32-bit or 64-bit.\n#include <stdio.h>\n\nint sGetDllType(const char *dll_name);\n\nint main()\n{\n int ret;\n const char *fname = \"sample_32.dll\";\n //const char *fname = \"sample_64.dll\";\n ret = sGetDllType(fname);\n}\n\nstatic int sGetDllType(const char *dll_name) {\n const int PE_POINTER_OFFSET = 60;\n const int MACHINE_TYPE_OFFSET = 4;\n FILE *fp;\n unsigned int ret = 0;\n int peoffset;\n unsigned short machine;\n\n fp = fopen(dll_name, \"rb\");\n unsigned char data[4096];\n ret = fread(data, sizeof(char), 4096, fp);\n fclose(fp);\n if (ret == 0)\n return -1;\n\n if ( (data[0] == 'M') && (data[1] == 'Z') ) {\n // Initial magic header is good\n peoffset = data[PE_POINTER_OFFSET + 3];\n peoffset = (peoffset << 8) + data[PE_POINTER_OFFSET + 2];\n peoffset = (peoffset << 8) + data[PE_POINTER_OFFSET + 1];\n peoffset = (peoffset << 8) + data[PE_POINTER_OFFSET];\n\n // Check second header\n if ((data[peoffset] == 'P') && (data[peoffset + 1] == 'E')) {\n machine = data[peoffset + MACHINE_TYPE_OFFSET];\n machine = (machine)+(data[peoffset + MACHINE_TYPE_OFFSET + 1] << 8);\n\n if (machine == 0x014c)\n return 32;\n if (machine == 0x8664)\n return 64;\n\n return -1;\n }\n return -1;\n }\n else\n return -1;\n}\n</code></pre>\n"
},
{
"answer_id": 51278133,
"author": "Saad Saadi",
"author_id": 1111249,
"author_profile": "https://Stackoverflow.com/users/1111249",
"pm_score": 2,
"selected": false,
"text": "<p><code>dumpbin.exe</code> available under <code>bin</code> directory of Visual Studio works for both <code>.lib</code> and <code>.dll</code> </p>\n\n<pre><code> dumpbin.exe /headers *.dll |findstr machine\n dumpbin.exe /headers *.lib |findstr machine\n</code></pre>\n"
},
{
"answer_id": 66548864,
"author": "John Matthews",
"author_id": 8771014,
"author_profile": "https://Stackoverflow.com/users/8771014",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a C++ MFC console application that writes out the file header information. You can check the machine type (IMAGE_FILE_HEADER Machine member) or the IMAGE_FILE_32BIT_MACHINE flag in the Characteristics to see what platform the file is built for. See WinNT.h for more info on the structures.</p>\n<pre><code>#include "stdafx.h"\n\nint _tmain(int argc, TCHAR* argv[], TCHAR* envp[])\n{\n int nRetCode = 0;\n int nrd;\n\n IMAGE_DOS_HEADER idh;\n IMAGE_NT_HEADERS inth;\n IMAGE_FILE_HEADER ifh;\n\n // initialize MFC and print and error on failure\n if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))\n {\n _tprintf(_T("Fatal Error: MFC initialization failed\\n"));\n nRetCode = 1;\n return 1;\n }\n if (argc != 2) {\n _ftprintf(stderr, _T("Usage: %s filename\\n"), argv[0]);\n return 1;\n }\n // Try to open the file\n CFile ckf;\n CFileException ex;\n DWORD flags = CFile::modeRead | CFile::shareDenyNone;\n\n if (!ckf.Open(argv[1], flags, &ex)) {\n TCHAR szError[1024];\n ex.GetErrorMessage(szError, 1024);\n _tprintf_s(_T("Couldn't open file: %1024s"), szError);\n return 2;\n }\n\n // The following is adapted from:\n // https://stackoverflow.com/questions/495244/how-can-i-test-a-windows-dll-file-to-determine-if-it-is-32-bit-or-64-bit\n // https://stackoverflow.com/questions/46024914/how-to-parse-exe-file-and-get-data-from-image-dos-header-structure-using-c-and\n // Seek to beginning of file\n ckf.Seek(0, CFile::begin);\n\n // Read DOS header\n int nbytes = sizeof(IMAGE_DOS_HEADER);\n nrd = ckf.Read(&idh, nbytes);\n\n // The idh.e_lfanew member is the offset to the NT_HEADERS structure\n ckf.Seek(idh.e_lfanew, CFile::begin);\n\n // Read NT headers\n nbytes = sizeof(IMAGE_NT_HEADERS);\n nrd = ckf.Read(&inth, nbytes);\n\n ifh = inth.FileHeader;\n\n _ftprintf(stdout, _T("File machine type: "));\n switch (ifh.Machine) {\n case IMAGE_FILE_MACHINE_I386:\n _ftprintf(stdout, _T("I386\\n"));\n break;\n case IMAGE_FILE_MACHINE_IA64:\n _ftprintf(stdout, _T("IA64\\n"));\n break;\n case IMAGE_FILE_MACHINE_AMD64:\n _ftprintf(stdout, _T("AMD64\\n"));\n break;\n default:\n _ftprintf(stdout, _T("Unknown (%d = %X)\\n"), ifh.Machine, ifh.Machine);\n break;\n }\n\n // Write characteristics (see WinNT.h)\n _ftprintf(stdout, _T("Characteristics:\\n"));\n _ftprintf(stdout, _T("RELOCS_STRIPPED Relocation info stripped from file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("EXECUTABLE_IMAGE File is executable (i.e. no unresolved externel references): %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("LINE_NUMS_STRIPPED Line nunbers stripped from file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_LINE_NUMS_STRIPPED ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("LOCAL_SYMS_STRIPPED Local symbols stripped from file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_LOCAL_SYMS_STRIPPED ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("AGGRESIVE_WS_TRIM Agressively trim working set: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_AGGRESIVE_WS_TRIM ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("LARGE_ADDRESS_AWARE App can handle >2gb addresses: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("BYTES_REVERSED_LO Bytes of machine word are reversed: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_BYTES_REVERSED_LO ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("32BIT_MACHINE 32 bit word machine: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_32BIT_MACHINE ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("DEBUG_STRIPPED Debugging info stripped from file in .DBG file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_DEBUG_STRIPPED ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("REMOVABLE_RUN_FROM_SWAP If Image is on removable media, copy and run from the swap file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("NET_RUN_FROM_SWAP If Image is on Net, copy and run from the swap file: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_NET_RUN_FROM_SWAP ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("SYSTEM System File: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_SYSTEM ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("DLL File is a DLL: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_DLL ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("UP_SYSTEM_ONLY File should only be run on a UP machine: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_UP_SYSTEM_ONLY ? _T('Y') : _T('N')));\n _ftprintf(stdout, _T("BYTES_REVERSED_HI Bytes of machine word are reversed: %c\\n"),\n (ifh.Characteristics & IMAGE_FILE_BYTES_REVERSED_HI ? _T('Y') : _T('N')));\n\n\n ckf.Close();\n\n return nRetCode;\n}\n</code></pre>\n"
},
{
"answer_id": 67739487,
"author": "risingballs",
"author_id": 1177068,
"author_profile": "https://Stackoverflow.com/users/1177068",
"pm_score": 0,
"selected": false,
"text": "<p>Here's another solution using C/C++ as a standalone tool, ready to be adapted to whatever you need:</p>\n<pre><code>// Fri May 28, 2021 -two\n\n#include <stdio.h>\n#include <io.h>\n#include <stdint.h>\n#include <iostream.h>\nusing namespace std;\n\nbool queryExeMachineType( const char *filename )\n{\n FILE *fp = fopen( filename, "rb" );\n\n if (fp == NULL)\n return false;\n\n // DOS header is 64 bytes\n const uint32_t fsize = filelength( fileno( fp ) );\n char magic[ 2 ] = { 0 };\n uint32_t offset = 0;\n uint16_t machine = 0;\n\n if (fread( magic, 1, 2, fp ) != 2 || magic[ 0 ] != 'M' || magic[ 1 ] != 'Z')\n {\n cerr << "not an executable file" << endl;\n fclose( fp );\n return false;\n }\n fseek( fp, 60, SEEK_SET );\n fread( &offset, 1, 4, fp );\n\n if (offset >= fsize)\n {\n cerr << "invalid pe offset" << endl;\n fclose( fp );\n return false;\n }\n fseek( fp, offset, SEEK_SET );\n\n if (fread( magic, 1, 2, fp ) != 2 || magic[ 0 ] != 'P' || magic[ 1 ] != 'E')\n {\n cerr << "not a pe executable" << endl;\n fclose( fp );\n return false;\n }\n fread( magic, 1, 2, fp );\n fread( &machine, 1, 2, fp );\n\n switch (machine)\n {\n case 0x014c:\n cout << "i386" << endl; // x86\n break;\n\n case 0x8664:\n cout << "amd64" << endl; // x86_64\n break;\n\n case 0x0200:\n cout << "ia64" << endl; // itanium\n break;\n\n default:\n cerr << "unknown machine 0x" << hex << machine << endl;\n break;\n }\n fclose( fp );\n return true;\n}\n\nint main( int argc, char *argv[] )\n{\n const char *fn = (argc > 1) ? argv[ 1 ] : "test.dll";\n\n if (queryExeMachineType( fn ))\n cerr << "succeeded" << endl;\n else\n cerr << "failed" << endl;\n\n return 0;\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/371953/"
] |
Hoi!
I have a form I wish to submit, but I need to add the PHPSESSID, because some clients allow no cookies.
There are several javascript functions on my page which displays a list of users (search, sort, open details), the page is generated by PHP.
Now I am looking for an elegant way to have the PHPSESSID included in every submit of my form - this needs to be done on several pages, so I hope for an easy solution. Adding the PHPSESSID to the action or into a hidden field does not work properly.
Or is this problem located elsewhere? It could be the client is behind a too restrictive firewall or something. Any ideas (especially with solutions ;-) ) in that direction are also welcome!
Example code (extremely simplified):
```
<form name="userlist" method="POST" action="./myuserlist.php">
[...some formfields and stuff..]
</form>
<script>
//one example function, there are several on my page
function next_page()
{
//set some hidden field to get the next page
document.forms[0].submit();
}
</script>
```
Thanks in advance!
Bye,
Basty
**[EDIT]**
session.use\_trans\_sid is set to true
|
(from another Q, since removed)
Machine type: This is a quick little bit of code I based on some that gets the linker timestamp. This is in the same header, and it seems to work - it returns I386 when compiled -any cpu-, and x64 when compiled with that as the target platform.
The Exploring PE Headers (K. Stanton,MSDN) blog entry that showed me the offset, as another response noted.
```
public enum MachineType {
Native = 0, I386 = 0x014c, Itanium = 0x0200, x64 = 0x8664
}
public static MachineType GetMachineType(string fileName)
{
const int PE_POINTER_OFFSET = 60;
const int MACHINE_OFFSET = 4;
byte[] data = new byte[4096];
using (Stream s = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
s.Read(data, 0, 4096);
}
// dos header is 64 bytes, last element, long (4 bytes) is the address of the PE header
int PE_HEADER_ADDR = BitConverter.ToInt32(data, PE_POINTER_OFFSET);
int machineUint = BitConverter.ToUInt16(data, PE_HEADER_ADDR + MACHINE_OFFSET);
return (MachineType)machineUint;
}
```
|
197,976 |
<p>I'm trying to write a Windows cmd script to perform several tasks in series.
However, it always stops after the first command in the script.</p>
<p>The command it stops after is a maven build (not sure if that's relevant).</p>
<p>How do I make it carry on and run each task in turn please?</p>
<p>Installing any software or configuring the registry etc is completely out of the question - it has to work on a vanilla Windows XP installation I'm afraid.</p>
<p>Ideally I'd like the script to abort if any of the commands failed, but that's a "nice to have", not essential.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 197997,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 8,
"selected": true,
"text": "<p>When you call another .bat file, I think you need \"call\" in front of the call:</p>\n\n<pre><code>call otherCommand.bat\n</code></pre>\n"
},
{
"answer_id": 198002,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know the direct answer to your question, but if you do a lot of these scripts, it might be worth learning a more powerful language like perl. Free implementations exist for Windows (e.g. activestate, cygwin). I've found it worth the initial effort for my own tasks.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>As suggested by @Ferruccio, if you can't install extra software, consider vbscript and/or javascript. They're built into the Windows scripting host.</p>\n"
},
{
"answer_id": 198011,
"author": "Steve",
"author_id": 15470,
"author_profile": "https://Stackoverflow.com/users/15470",
"pm_score": 6,
"selected": false,
"text": "<p>You can use the && symbol between commands to execute the second command only if the first succeeds. More info here <a href=\"http://commandwindows.com/command1.htm\" rel=\"noreferrer\">http://commandwindows.com/command1.htm</a></p>\n"
},
{
"answer_id": 198042,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 5,
"selected": false,
"text": "<p>Not sure why the first command is stopping.\nIf you can make it parallel, you can try something like </p>\n\n<pre><code>start cmd.exe /C 1.bat \nstart cmd.exe /C 2.bat\n</code></pre>\n"
},
{
"answer_id": 4437001,
"author": "Pulendar Vadde",
"author_id": 541635,
"author_profile": "https://Stackoverflow.com/users/541635",
"pm_score": 1,
"selected": false,
"text": "<p>If you are running in Windows you can use the following command.</p>\n\n<p>Drive:</p>\n\n<pre><code>cd \"Script location\"\nschtasks /run /tn \"TASK1\"\nschtasks /run /tn \"TASK2\"\nschtasks /run /tn \"TASK3\"\nexit\n</code></pre>\n"
},
{
"answer_id": 7848054,
"author": "mhollander38",
"author_id": 595807,
"author_profile": "https://Stackoverflow.com/users/595807",
"pm_score": 5,
"selected": false,
"text": "<p>I have just been doing the exact same(ish) task of creating a batch script to run maven test scripts. The problem is that calling maven scrips with mvn clean install ... is itself a script and so needs to be done with call mvn clean install.</p>\n\n<p>Code that will work</p>\n\n<pre><code>rem run a maven clean install\ncd C:\\rbe-ui-test-suite \ncall mvn clean install\nrem now run through all the test scripts\ncall mvn clean install -Prun-integration-tests -Dpattern=tc-login\ncall mvn clean install -Prun-integration-tests -Dpattern=login-1\n</code></pre>\n\n<p>Note rather the use of call. This will allow the use of consecutive maven scripts in the batch file.</p>\n"
},
{
"answer_id": 24951390,
"author": "Pushkar",
"author_id": 2528433,
"author_profile": "https://Stackoverflow.com/users/2528433",
"pm_score": 0,
"selected": false,
"text": "<p>Note that you don't need semicolons in batch files. And the reason why you need to use call is that mvn itself is a batch file and batch files need to call each other with call, otherwise control does not return to the caller.</p>\n"
},
{
"answer_id": 46384998,
"author": "JSON C11",
"author_id": 1244127,
"author_profile": "https://Stackoverflow.com/users/1244127",
"pm_score": 3,
"selected": false,
"text": "<p>Using double ampersands will run the second command, only if the first one succeeds:</p>\n\n<pre><code>cd Desktop/project-directory && atom .\n</code></pre>\n\n<p>Where as, using only one ampersand will attempt to run both commands, even if the first fails:</p>\n\n<pre><code>cd Desktop/project-directory & atom .\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151/"
] |
I'm trying to write a Windows cmd script to perform several tasks in series.
However, it always stops after the first command in the script.
The command it stops after is a maven build (not sure if that's relevant).
How do I make it carry on and run each task in turn please?
Installing any software or configuring the registry etc is completely out of the question - it has to work on a vanilla Windows XP installation I'm afraid.
Ideally I'd like the script to abort if any of the commands failed, but that's a "nice to have", not essential.
Thanks.
|
When you call another .bat file, I think you need "call" in front of the call:
```
call otherCommand.bat
```
|
197,986 |
<p>For example:</p>
<pre><code>javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
</code></pre>
|
[
{
"answer_id": 197993,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 10,
"selected": true,
"text": "<p>This comes up in Java 5 and later if you're using collections without type specifiers (e.g., <code>Arraylist()</code> instead of <code>ArrayList<String>()</code>). It means that the compiler can't check that you're using the collection in a type-safe way, using <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html\" rel=\"noreferrer\">generics</a>.</p>\n<p>To get rid of the warning, you need to be specific about what type of objects you're storing in the collection. So, instead of</p>\n<pre><code>List myList = new ArrayList();\n</code></pre>\n<p>use</p>\n<pre><code>List<String> myList = new ArrayList<String>();\n</code></pre>\n<hr />\n<p>In Java 7 you can shorten generic instantiation by using <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html\" rel=\"noreferrer\">Type Inference</a>.</p>\n<pre><code>List<String> myList = new ArrayList<>();\n</code></pre>\n"
},
{
"answer_id": 197998,
"author": "Matt",
"author_id": 20630,
"author_profile": "https://Stackoverflow.com/users/20630",
"pm_score": 3,
"selected": false,
"text": "<p>for example when you call a function that returns Generic Collections and you don't specify the generic parameters yourself.</p>\n\n<p>for a function</p>\n\n<pre><code>List<String> getNames()\n\n\nList names = obj.getNames();\n</code></pre>\n\n<p>will generate this error.</p>\n\n<p>To solve it you would just add the parameters</p>\n\n<pre><code>List<String> names = obj.getNames();\n</code></pre>\n"
},
{
"answer_id": 198000,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 3,
"selected": false,
"text": "<p>The \"unchecked or unsafe operations\" warning was added when java added <a href=\"http://java.sun.com/docs/books/tutorial/java/generics/index.html\" rel=\"nofollow noreferrer\">Generics</a>, if I remember correctly. It's usually asking you to be more explicit about types, in one way or another. </p>\n\n<p>For example. the code <code>ArrayList foo = new ArrayList();</code> triggers that warning because javac is looking for <code>ArrayList<String> foo = new ArrayList<String>();</code></p>\n"
},
{
"answer_id": 198053,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 8,
"selected": false,
"text": "<p>If you do what it suggests and recompile with the \"-Xlint:unchecked\" switch, it will give you more detailed information.</p>\n\n<p>As well as the use of raw types (as described by the other answers), an unchecked cast can also cause the warning.</p>\n\n<p>Once you've compiled with -Xlint, you should be able to rework your code to avoid the warning. This is not always possible, particularly if you are integrating with legacy code that cannot be changed. In this situation, you may decide to suppress the warning in places where you know that the code is correct:</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\npublic void myMethod()\n{\n //...\n}\n</code></pre>\n"
},
{
"answer_id": 23908919,
"author": "Suganthan Madhavan Pillai",
"author_id": 2534236,
"author_profile": "https://Stackoverflow.com/users/2534236",
"pm_score": 4,
"selected": false,
"text": "<p>This warning means that your code operates on a raw type, recompile the example with the </p>\n\n<pre><code>-Xlint:unchecked \n</code></pre>\n\n<p>to get the details </p>\n\n<p>like this: </p>\n\n<pre><code>javac YourFile.java -Xlint:unchecked\n\nMain.java:7: warning: [unchecked] unchecked cast\n clone.mylist = (ArrayList<String>)this.mylist.clone();\n ^\n required: ArrayList<String>\n found: Object\n1 warning\n</code></pre>\n\n<p>docs.oracle.com talks about it here: \n<a href=\"http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html\" rel=\"noreferrer\">http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html</a></p>\n"
},
{
"answer_id": 25913061,
"author": "Julius",
"author_id": 3942879,
"author_profile": "https://Stackoverflow.com/users/3942879",
"pm_score": 1,
"selected": false,
"text": "<p>The solution would be to use specific type in <code><></code> like <code>ArrayList<File></code>.</p>\n\n<p>example: </p>\n\n<pre><code>File curfolder = new File( \"C:\\\\Users\\\\username\\\\Desktop\");\nFile[] file = curfolder.listFiles();\nArrayList filename = Arrays.asList(file);\n</code></pre>\n\n<p>above code generate warning because <code>ArrayList</code> is not of specific type.</p>\n\n<pre><code>File curfolder = new File( \"C:\\\\Users\\\\username\\\\Desktop\");\nFile[] file = curfolder.listFiles();\nArrayList<File> filename = Arrays.asList(file);\n</code></pre>\n\n<p>above code will do fine. Only change is in third line after <code>ArrayList</code>.</p>\n"
},
{
"answer_id": 29502285,
"author": "Michael Levy",
"author_id": 90236,
"author_profile": "https://Stackoverflow.com/users/90236",
"pm_score": 2,
"selected": false,
"text": "<p>I just want to add one example of the kind of unchecked warning I see quite often. If you use classes that implement an interface like Serializable, often you will call methods that return objects of the interface, and not the actual class. If the class being returned must be cast to a type based on generics, you can get this warning. </p>\n\n<p>Here is a brief (and somewhat silly) example to demonstrate:</p>\n\n<pre><code>import java.io.Serializable;\n\npublic class SimpleGenericClass<T> implements Serializable {\n\n public Serializable getInstance() {\n return this;\n }\n\n // @SuppressWarnings(\"unchecked\")\n public static void main() {\n\n SimpleGenericClass<String> original = new SimpleGenericClass<String>();\n\n // java: unchecked cast\n // required: SimpleGenericClass<java.lang.String>\n // found: java.io.Serializable\n SimpleGenericClass<String> returned =\n (SimpleGenericClass<String>) original.getInstance();\n }\n}\n</code></pre>\n\n<p>getInstance() returns an object that implements Serializable. This must be cast to the actual type, but this is an unchecked cast.</p>\n"
},
{
"answer_id": 53265164,
"author": "Borzh",
"author_id": 1223728,
"author_profile": "https://Stackoverflow.com/users/1223728",
"pm_score": 5,
"selected": false,
"text": "<p>For Android Studio, you need to add:</p>\n\n<pre><code>allprojects {\n\n gradle.projectsEvaluated {\n tasks.withType(JavaCompile) {\n options.compilerArgs << \"-Xlint:unchecked\"\n }\n }\n\n // ...\n}\n</code></pre>\n\n<p>in your project's build.gradle file to know where this error is produced.</p>\n"
},
{
"answer_id": 57107212,
"author": "Mayukh Datta",
"author_id": 7936081,
"author_profile": "https://Stackoverflow.com/users/7936081",
"pm_score": 0,
"selected": false,
"text": "<p>You can keep it in the generic form and write it as:</p>\n<pre><code>// list 2 is made generic and can store any type of Object\nArrayList<Object> list2 = new ArrayList<Object>();\n</code></pre>\n<p>Setting type of <code>ArrayList</code> as <code>Object</code> gives us the advantage to store any type of data. You don't need to use -Xlint or anything else.</p>\n"
},
{
"answer_id": 58098917,
"author": "Oskar",
"author_id": 2534288,
"author_profile": "https://Stackoverflow.com/users/2534288",
"pm_score": 3,
"selected": false,
"text": "<p>I had 2 years old classes and some new classes. I solved it in Android Studio as follows:</p>\n\n<pre><code>allprojects {\n\n gradle.projectsEvaluated {\n tasks.withType(JavaCompile) {\n options.compilerArgs << \"-Xlint:unchecked\"\n }\n }\n\n}\n</code></pre>\n\n<p>In my project build.gradle file (<a href=\"https://stackoverflow.com/users/1223728/borzh\">Borzh solution</a>)</p>\n\n<p>And then if some Metheds is left:</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\npublic void myMethod()\n{\n //...\n}\n</code></pre>\n"
},
{
"answer_id": 59188558,
"author": "Mahadi Hasan",
"author_id": 9471958,
"author_profile": "https://Stackoverflow.com/users/9471958",
"pm_score": 0,
"selected": false,
"text": "<p>This warning also could be raised due to <code>new HashMap()</code> or <code>new ArrayList()</code> that is generic type has to be specific otherwise the compiler will generate warning.</p>\n<p>Please make sure that if you code contains the following you have to change accordingly</p>\n<pre><code>new HashMap() => Map<String,Object> map = new HashMap<String,Object>()\nnew HashMap() => Map<String,Object> map = new HashMap<>()\n\nnew ArrayList() => List<String,Object> map = new ArrayList<String,Object>()\nnew ArrayList() => List<String,Object> map = new ArrayList<>()\n</code></pre>\n"
},
{
"answer_id": 61384313,
"author": "CoolMind",
"author_id": 2914140,
"author_profile": "https://Stackoverflow.com/users/2914140",
"pm_score": 0,
"selected": false,
"text": "<p>I have <code>ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;</code>. Because <code>value</code> is a complex structure (I want to <a href=\"https://stackoverflow.com/a/54709501/2914140\">clean JSON</a>), there can happen any combinations on numbers, booleans, strings, arrays. So, I used the solution of @Dan Dyer:</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\nArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23987/"
] |
For example:
```
javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
```
|
This comes up in Java 5 and later if you're using collections without type specifiers (e.g., `Arraylist()` instead of `ArrayList<String>()`). It means that the compiler can't check that you're using the collection in a type-safe way, using [generics](http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html).
To get rid of the warning, you need to be specific about what type of objects you're storing in the collection. So, instead of
```
List myList = new ArrayList();
```
use
```
List<String> myList = new ArrayList<String>();
```
---
In Java 7 you can shorten generic instantiation by using [Type Inference](http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html).
```
List<String> myList = new ArrayList<>();
```
|
197,987 |
<p>I have a main frame with a splitter. On the left I have my (imaginatively named) CAppView_Leftand on the right I have CAppView_Right_1and CAppView_Right_2. Through the following code I initialise the two primary views correctly:</p>
<pre><code>if (!m_wndSplitter.CreateStatic(this, 1, 2))
{
TRACE0("Failed to CreateStaticSplitter\n");
return FALSE;
}
else
if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CAppView_Left), CSize(300, 200), pContext))
{
TRACE0("Failed to create left pane\n");
return FALSE;
}
else
if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CAppView_Right_1), CSize(375, 200), pContext))
{
TRACE0("Failed to create first right pane\n");
return FALSE;
}
</code></pre>
<p>...</p>
<p>What I would like to do is create a second view inside the right frame, however when I try to add this:</p>
<pre><code>if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CAppView_Right_2), CSize(375, 200), pContext))
{
TRACE0("Failed to create first right pane\n");
return FALSE;
}
</code></pre>
<p>VS compiles but fails to run the application, raising an exception telling me I have already defined the view.</p>
<p>Can someone suggest how I do this? Also, how to change between the views from either a view or the document class?</p>
|
[
{
"answer_id": 198142,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 0,
"selected": false,
"text": "<p>You can't create a second right hand view because your </p>\n\n<pre><code>m_wndSplitter.CreateStatic(this, 1, 2) \n</code></pre>\n\n<p>has only created two columns. You could change this to </p>\n\n<pre><code>m_wndSplitter.CreateStatic(this, 1, 3)\n</code></pre>\n\n<p>and change your second right view to</p>\n\n<pre><code>if (!m_wndSplitter.CreateView(0, 2, RUNTIME_CLASS(CAppView_Right_2), CSize(375, 200), pContext))\n{ \nTRACE0(\"Failed to create first right pane\\n\"); \n return FALSE;\n}\n</code></pre>\n\n<p>This results in three columns each with a seperate view. You could also create an additional splitter window to split one of the existing views, e.g. something like</p>\n\n<pre><code>m_wndSplitter2.CreateStatic(m_View2, 2, 1)\n</code></pre>\n\n<p>where m_view2 was your second view</p>\n"
},
{
"answer_id": 198308,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 2,
"selected": true,
"text": "<p>There is a CodeProject article that should help you achieve what you want:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/splitter/usefulsplitter.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/splitter/usefulsplitter.aspx</a></p>\n\n<p>I have replaced views in a splitter before, so if the above doesn't help I'll post some of my own code.</p>\n"
},
{
"answer_id": 198350,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 0,
"selected": false,
"text": "<p>To switch between views, you'll need to explicitly DeleteView before creating another view in its place.</p>\n\n<p>If you need to preserve the state of the interchangeable views, you'd better make the views be able to initialize their state from the document. Be careful to update the document with any state that needs to stick around between deletion and re-creation of one of the views.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
I have a main frame with a splitter. On the left I have my (imaginatively named) CAppView\_Leftand on the right I have CAppView\_Right\_1and CAppView\_Right\_2. Through the following code I initialise the two primary views correctly:
```
if (!m_wndSplitter.CreateStatic(this, 1, 2))
{
TRACE0("Failed to CreateStaticSplitter\n");
return FALSE;
}
else
if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CAppView_Left), CSize(300, 200), pContext))
{
TRACE0("Failed to create left pane\n");
return FALSE;
}
else
if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CAppView_Right_1), CSize(375, 200), pContext))
{
TRACE0("Failed to create first right pane\n");
return FALSE;
}
```
...
What I would like to do is create a second view inside the right frame, however when I try to add this:
```
if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CAppView_Right_2), CSize(375, 200), pContext))
{
TRACE0("Failed to create first right pane\n");
return FALSE;
}
```
VS compiles but fails to run the application, raising an exception telling me I have already defined the view.
Can someone suggest how I do this? Also, how to change between the views from either a view or the document class?
|
There is a CodeProject article that should help you achieve what you want:
<http://www.codeproject.com/KB/splitter/usefulsplitter.aspx>
I have replaced views in a splitter before, so if the above doesn't help I'll post some of my own code.
|
198,006 |
<p>I need a way to do key-value lookups across (potentially) hundreds of GB of data. Ideally something based on a distributed hashtable, that works nicely with Java. It should be fault-tolerant, and open source.</p>
<p>The store should be persistent, but would ideally cache data in memory to speed things up.</p>
<p>It should be able to support concurrent reads and writes from multiple machines (reads will be 100X more common though). Basically the purpose is to do a quick initial lookup of user metadata for a web-service.</p>
<p>Can anyone recommend anything?</p>
|
[
{
"answer_id": 198017,
"author": "carson",
"author_id": 25343,
"author_profile": "https://Stackoverflow.com/users/25343",
"pm_score": 1,
"selected": false,
"text": "<p>You should probably specify if it needs to be persistent or not, in memory or not, etc. You could try: <a href=\"http://www.danga.com/memcached/\" rel=\"nofollow noreferrer\">http://www.danga.com/memcached/</a></p>\n"
},
{
"answer_id": 198019,
"author": "Ryan Stille",
"author_id": 10876,
"author_profile": "https://Stackoverflow.com/users/10876",
"pm_score": -1,
"selected": false,
"text": "<p>DNS has the capability to do this, I don't know how large each one of your records is (8GB of tons of small data?), but it may work.</p>\n"
},
{
"answer_id": 198029,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://open-chord.sourceforge.net/\" rel=\"noreferrer\">Open Chord</a> is an implementation of the <a href=\"http://en.wikipedia.org/wiki/Chord_(DHT)\" rel=\"noreferrer\">CHORD</a> protocol in Java. It is a distributed hash table protocol that should fit your needs perfectly.</p>\n"
},
{
"answer_id": 198060,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Distributed hash tables include Tapestry, Chord, and Pastry. One of these should suit your needs.</p>\n"
},
{
"answer_id": 198076,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "<p>OpenChord sounds promising; but i'd also consider <a href=\"http://www.oracle.com/technology/products/berkeley-db/index.html\" rel=\"nofollow noreferrer\">BDB</a>, or any other non-SQL hashtable, making it distributed can be dead-easy (if the number of storage nodes is (almost) constant, at least), just hash the key on the client to get the appropriate server.</p>\n"
},
{
"answer_id": 199828,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://java-source.net/open-source/cache-solutions\" rel=\"nofollow noreferrer\">Open Source Cache Solutions in Java</a></p>\n\n<p><a href=\"http://www.oracle.com/technology/products/coherence/index.html\" rel=\"nofollow noreferrer\">Oracle Coherence</a> (used to be Tangosol)</p>\n\n<p><a href=\"http://jcp.org/en/jsr/detail?id=107\" rel=\"nofollow noreferrer\">JCache JSR</a></p>\n"
},
{
"answer_id": 203402,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on the use case, <a href=\"http://terracotta.org\" rel=\"nofollow noreferrer\">Terracotta</a> may be just what you need. </p>\n"
},
{
"answer_id": 228958,
"author": "Phillip B Oldham",
"author_id": 30478,
"author_profile": "https://Stackoverflow.com/users/30478",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://blitiri.com.ar/p/nmdb/\" rel=\"nofollow noreferrer\">nmdb</a> sounds like its exactly what you need. Distributed, in memory cache, with a persistent on-disk storage. Current back-ends include qdbm, berkeley db, and (recently added after a quick email to the developer) <a href=\"http://tokyocabinet.sourceforge.net/index.html\" rel=\"nofollow noreferrer\">tokyo cabinet</a>. key/value size is limited though, but I believe that can be lifted if you don't need TICP support.</p>\n"
},
{
"answer_id": 247624,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>You might want to check out <a href=\"http://www.hazelcast.com\" rel=\"noreferrer\">Hazelcast</a>. It is distributed/partitioned, super lite, easy and free.</p>\n\n<pre><code>java.util.Map map = Hazelcast.getMap (\"mymap\");\nmap.put (\"key1\", \"value1\");\n</code></pre>\n\n<p>Regards,</p>\n\n<p>-talip</p>\n"
},
{
"answer_id": 21073621,
"author": "Nikita Koksharov",
"author_id": 764206,
"author_profile": "https://Stackoverflow.com/users/764206",
"pm_score": 0,
"selected": false,
"text": "<p>Try distributed Map structure from <a href=\"https://redisson.org\" rel=\"nofollow noreferrer\">Redisson</a>, it based on <a href=\"http://redis.io/\" rel=\"nofollow noreferrer\">Redis</a> server. Using Redis cluster configuration you may split data across 1000 servers.</p>\n\n<p>Usage example:</p>\n\n<pre><code>Redisson redisson = Redisson.create();\n\nConcurrentMap<String, SomeObject> map = redisson.getMap(\"anyMap\");\nmap.put(\"123\", new SomeObject());\nmap.putIfAbsent(\"323\", new SomeObject());\nmap.remove(\"123\");\n\n...\n\nredisson.shutdown();\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16050/"
] |
I need a way to do key-value lookups across (potentially) hundreds of GB of data. Ideally something based on a distributed hashtable, that works nicely with Java. It should be fault-tolerant, and open source.
The store should be persistent, but would ideally cache data in memory to speed things up.
It should be able to support concurrent reads and writes from multiple machines (reads will be 100X more common though). Basically the purpose is to do a quick initial lookup of user metadata for a web-service.
Can anyone recommend anything?
|
You might want to check out [Hazelcast](http://www.hazelcast.com). It is distributed/partitioned, super lite, easy and free.
```
java.util.Map map = Hazelcast.getMap ("mymap");
map.put ("key1", "value1");
```
Regards,
-talip
|
198,007 |
<p>I'm using the PHP function imagettftext() to convert text into a GIF image. The text I am converting has Unicode characters including Japanese. Everything works fine on my local machine (Ubuntu 7.10), but on my webhost server, the Japanese characters are mangled. What could be causing the difference? Everything should be encoded as UTF-8.</p>
<p>Broken Image on webhost server:
<a href="http://www.ibeni.net/flashcards/imagetest.php" rel="noreferrer">http://www.ibeni.net/flashcards/imagetest.php</a></p>
<p>Copy of correct image from my local machine:
<a href="http://www.ibeni.net/flashcards/imagetest.php.gif" rel="noreferrer">http://www.ibeni.net/flashcards/imagetest.php.gif</a></p>
<p>Copy of phpinfo() from my local machine:
<a href="http://www.ibeni.net/flashcards/phpinfo.php.html" rel="noreferrer">http://www.ibeni.net/flashcards/phpinfo.php.html</a></p>
<p>Copy of phpinfo() from my webhost server:
<a href="http://example5.nfshost.com/phpinfo" rel="noreferrer">http://example5.nfshost.com/phpinfo</a></p>
<p>Code:</p>
<pre><code>mb_language('uni');
mb_internal_encoding('UTF-8');
header('Content-type: image/gif');
$text = '日本語';
$font = './Cyberbit.ttf';
// Create the image
$im = imagecreatetruecolor(160, 160);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// Create some colors
imagefilledrectangle($im, 0, 0, 159, 159, $white);
// Add the text
imagettftext($im, 12, 0, 20, 20, $black, $font, $text);
imagegif($im);
imagedestroy($im);
</code></pre>
|
[
{
"answer_id": 198054,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "<p>My prime suspect is the font you are using for rendering.</p>\n\n<p>According to <a href=\"http://fr3.php.net/imagettftext\" rel=\"nofollow noreferrer\">http://fr3.php.net/imagettftext</a>, different versions of the GD library used by php can show different behaviour.</p>\n\n<ul>\n<li>GD Version on your local machine: \n2.0 or higher </li>\n<li>GD Version on your webhost server: bundled (2.0.34 compatible)</li>\n</ul>\n\n<p><em>Edit:</em>\nAnother idea: can you verify that <code>$text = '日本語';</code> is really saved like this on your production server? Maybe there is an encoding problem with your script.</p>\n\n<p><em>Next edit:</em> BKB already proposed that. So in case this is the cause: he was first with the answer ;-)</p>\n"
},
{
"answer_id": 198294,
"author": "Jordan S. Jones",
"author_id": 27536,
"author_profile": "https://Stackoverflow.com/users/27536",
"pm_score": -1,
"selected": false,
"text": "<p>Does that particular font file exist on your production machine? If using FTP to upload your files, are you using binary encoding?</p>\n"
},
{
"answer_id": 201787,
"author": "gerdemb",
"author_id": 27478,
"author_profile": "https://Stackoverflow.com/users/27478",
"pm_score": 5,
"selected": true,
"text": "<p>Here's the solution that finally worked for me:</p>\n\n<pre><code>$text = \"你好\";\n// Convert UTF-8 string to HTML entities\n$text = mb_convert_encoding($text, 'HTML-ENTITIES',\"UTF-8\");\n// Convert HTML entities into ISO-8859-1\n$text = html_entity_decode($text,ENT_NOQUOTES, \"ISO-8859-1\");\n// Convert characters > 127 into their hexidecimal equivalents\n$out = \"\";\nfor($i = 0; $i < strlen($text); $i++) {\n $letter = $text[$i];\n $num = ord($letter);\n if($num>127) {\n $out .= \"&#$num;\";\n } else {\n $out .= $letter;\n }\n}\n</code></pre>\n\n<p>Converting the string to HTML entities works except that the function imagettftext() doesn't accept named entities. For example,</p>\n\n<pre><code>&#26085;&#26412;&#35486;\n</code></pre>\n\n<p>is OK, but </p>\n\n<pre><code>&ccedil;\n</code></pre>\n\n<p>is not. Converting back to ISO-8859-1, converts the named entities back to characters, but there is a second problem. imagettftext() doesn't support characters with a value greater than >127. The final for-loop encodes these characters in hexadecimal. This solution is working for me with the text that I am using (includes Japanese, Chinese and accented latin characters for Portuguese), but I'm not 100% sure it will work in all cases.</p>\n\n<p>All of these gymnastics are needed because imagettftext() doesn't really accept UTF-8 strings on my server.</p>\n"
},
{
"answer_id": 1956361,
"author": "amphetamachine",
"author_id": 237955,
"author_profile": "https://Stackoverflow.com/users/237955",
"pm_score": 4,
"selected": false,
"text": "<p>I have been having the same problem with a script that will render text in an image and output it. Problem was, that due to different browsers (or code hardiness/paranoia, whichever way you want to think of it), I had no way of knowing what encoding was being put inside the <code>$_GET</code> array.</p>\n\n<p>Here is how I solved the problem.</p>\n\n<pre><code>$item_text = $_GET['text'];\n\n# detect if the string was passed in as unicode\n$text_encoding = mb_detect_encoding($item_text, 'UTF-8, ISO-8859-1');\n# make sure it's in unicode\nif ($text_encoding != 'UTF-8') {\n $item_text = mb_convert_encoding($item_text, 'UTF-8', $text_encoding);\n}\n\n# html numerically-escape everything (&#[dec];)\n$item_text = mb_encode_numericentity($item_text,\n array (0x0, 0xffff, 0, 0xffff), 'UTF-8');\n</code></pre>\n\n<p>This solves any problem with <code>imagettftext</code> not being able to handle characters above #127 by simply changing ALL the characters (including multibyte Unicode characters) into their HTML numeric character entity—\"&#65;\" for \"A\", \"&#66;\" for \"B\", etc.—which the <a href=\"http://www.php.net/imagettftext\" rel=\"noreferrer\">manual page</a> claims support for.</p>\n"
},
{
"answer_id": 3922075,
"author": "obi",
"author_id": 474245,
"author_profile": "https://Stackoverflow.com/users/474245",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem. Converting font from otf to ttf helped. You can use FontForge (available in standard repository) to convert.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27478/"
] |
I'm using the PHP function imagettftext() to convert text into a GIF image. The text I am converting has Unicode characters including Japanese. Everything works fine on my local machine (Ubuntu 7.10), but on my webhost server, the Japanese characters are mangled. What could be causing the difference? Everything should be encoded as UTF-8.
Broken Image on webhost server:
<http://www.ibeni.net/flashcards/imagetest.php>
Copy of correct image from my local machine:
<http://www.ibeni.net/flashcards/imagetest.php.gif>
Copy of phpinfo() from my local machine:
<http://www.ibeni.net/flashcards/phpinfo.php.html>
Copy of phpinfo() from my webhost server:
<http://example5.nfshost.com/phpinfo>
Code:
```
mb_language('uni');
mb_internal_encoding('UTF-8');
header('Content-type: image/gif');
$text = '日本語';
$font = './Cyberbit.ttf';
// Create the image
$im = imagecreatetruecolor(160, 160);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// Create some colors
imagefilledrectangle($im, 0, 0, 159, 159, $white);
// Add the text
imagettftext($im, 12, 0, 20, 20, $black, $font, $text);
imagegif($im);
imagedestroy($im);
```
|
Here's the solution that finally worked for me:
```
$text = "你好";
// Convert UTF-8 string to HTML entities
$text = mb_convert_encoding($text, 'HTML-ENTITIES',"UTF-8");
// Convert HTML entities into ISO-8859-1
$text = html_entity_decode($text,ENT_NOQUOTES, "ISO-8859-1");
// Convert characters > 127 into their hexidecimal equivalents
$out = "";
for($i = 0; $i < strlen($text); $i++) {
$letter = $text[$i];
$num = ord($letter);
if($num>127) {
$out .= "&#$num;";
} else {
$out .= $letter;
}
}
```
Converting the string to HTML entities works except that the function imagettftext() doesn't accept named entities. For example,
```
日本語
```
is OK, but
```
ç
```
is not. Converting back to ISO-8859-1, converts the named entities back to characters, but there is a second problem. imagettftext() doesn't support characters with a value greater than >127. The final for-loop encodes these characters in hexadecimal. This solution is working for me with the text that I am using (includes Japanese, Chinese and accented latin characters for Portuguese), but I'm not 100% sure it will work in all cases.
All of these gymnastics are needed because imagettftext() doesn't really accept UTF-8 strings on my server.
|
198,024 |
<p>How do I go about doing this with jQuery?</p>
<p>Basically the structure:</p>
<pre><code><form id="myForm">
<iframe>
<!-- Normal HTML headers omitted -->
<input type=radio name="myRadio" value=1>First
<input type=radio name="myRadio" value=2>Second
<input type=radio name="myRadio" value=3>Third
</iframe>
<input type=button value="Submit" />
</form>
</code></pre>
<p>I tried various examples from the net such as </p>
<pre><code>$("input[@type=radio][@checked]");
</code></pre>
<p>But failed. Even with jQuery form plugin's <a href="http://malsup.com/jquery/form/#fields" rel="nofollow noreferrer">.fieldValue()</a> failed.</p>
|
[
{
"answer_id": 198094,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 5,
"selected": true,
"text": "<p>Try <code>$('#myForm iframe').contents().find('input[name=myradio]').val()</code></p>\n\n<p>I'll assume that the iframe contents have already been loaded and are accessible e.g same domain.</p>\n"
},
{
"answer_id": 198211,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "<p>Unless jQuery does some magic I'm not aware of, accessing another frame's DOM requires a little trickery. This may work:</p>\n\n<pre><code>var frameDocument = $('#myForm iframe').contentDocument || $('#myForm iframe').contentWindow.document;\n$(frameDocument).find('input[type=radio][checked]');\n</code></pre>\n\n<p>And, note this from the jQuery documentation:</p>\n\n<blockquote>\n <p>Note the \"@\" before the attribute name was deprecated as of version 1.2.</p>\n</blockquote>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15345/"
] |
How do I go about doing this with jQuery?
Basically the structure:
```
<form id="myForm">
<iframe>
<!-- Normal HTML headers omitted -->
<input type=radio name="myRadio" value=1>First
<input type=radio name="myRadio" value=2>Second
<input type=radio name="myRadio" value=3>Third
</iframe>
<input type=button value="Submit" />
</form>
```
I tried various examples from the net such as
```
$("input[@type=radio][@checked]");
```
But failed. Even with jQuery form plugin's [.fieldValue()](http://malsup.com/jquery/form/#fields) failed.
|
Try `$('#myForm iframe').contents().find('input[name=myradio]').val()`
I'll assume that the iframe contents have already been loaded and are accessible e.g same domain.
|
198,041 |
<p>Is there a way to tell the debugger to stop just before returning, on whichever statement exits from the method, be it return, exception, or fall out the bottom? I am inspired by the fact that the Java editor shows me all the places that my method <em>can</em> exit - it highlights them when you click on the return type of the method declaration, (Mark Occurrences enabled).</p>
<p>[eclipse 3.4]</p>
|
[
{
"answer_id": 198072,
"author": "MBCook",
"author_id": 18189,
"author_profile": "https://Stackoverflow.com/users/18189",
"pm_score": 0,
"selected": false,
"text": "<p>Good question. Off the top of my head, I'd do this:</p>\n\n<pre><code>public void method(Object stuff) {\n try {\n /* normal code */\n } finally {\n int x = 0;\n }\n}\n</code></pre>\n\n<p>You can set the breakpoint on the x = 0 line, and it will ALWAYS be executed no matter where you return. Even with an exception being thrown, it will be run.</p>\n\n<p>The catch to this is scope. Unless you define variables outside of the try block, you won't be able to see their values where you get to the finally block since they will have exited scope.</p>\n\n<p>Having to just place 5 breakpoints (one for each return statement, whatever) may work best.</p>\n\n<p>I hope there is a better way, I'd love to know it.</p>\n"
},
{
"answer_id": 198218,
"author": "idrosid",
"author_id": 17876,
"author_profile": "https://Stackoverflow.com/users/17876",
"pm_score": 6,
"selected": true,
"text": "<p>Put a breakpoint on the line of the method signature. That is where you write</p>\n\n<pre><code>public void myMethod() {\n</code></pre>\n\n<p>Then right-click on the breakpoint and select \"Breakpoint Properties\". At the bottom of the pop-up there are two checkboxes: \"Method Entry\", \"Method Exit\". Check the latter.</p>\n"
},
{
"answer_id": 198300,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 2,
"selected": false,
"text": "<p>You can set a method breakpoint. </p>\n\n<p>Double click in the margin next to the method declaration. A breakpoint with an arrow decoration appears. Right-clicking to examine the properties, you can set \"Suspend on:\" for \"Method Entry\" and/or \"Method Exit\".</p>\n\n<p>You can read more about them in the <a href=\"http://books.google.com/books?id=U4UuyIU6bZAC&pg=PA132&lpg=PA132&dq=%22method+breakpoint%22+%22eclipse%22&source=web&ots=eOj8Od5DLx&sig=g-cThDlC2pZ9Alvk5RD8fZ3-0TU&hl=en\" rel=\"nofollow noreferrer\">Eclipse Cookbook</a>.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
Is there a way to tell the debugger to stop just before returning, on whichever statement exits from the method, be it return, exception, or fall out the bottom? I am inspired by the fact that the Java editor shows me all the places that my method *can* exit - it highlights them when you click on the return type of the method declaration, (Mark Occurrences enabled).
[eclipse 3.4]
|
Put a breakpoint on the line of the method signature. That is where you write
```
public void myMethod() {
```
Then right-click on the breakpoint and select "Breakpoint Properties". At the bottom of the pop-up there are two checkboxes: "Method Entry", "Method Exit". Check the latter.
|
198,045 |
<p>I've got a spreadsheet with plenty of graphs in it and one sheet with loads of data feeding those graphs.</p>
<p>I've plotted the data on each graph using </p>
<pre><code>=Sheet1!$C5:$C$3000
</code></pre>
<p>This basically just plots the values in C5 to C3000 on a graph.</p>
<p>Regularly though I just want to look at a subset of the data i.e. I might just want to look at the first 1000 rows for example. Currently to do this I have to modify the formula in each of my graphs which takes time.</p>
<p>Would you know a way to simplify this? Ideally if I could just have a cell on single sheet that it reads in the row number from and plots all the graphs from C5 to C 'row number' would be best.</p>
<p>Any help would be much appreciated.</p>
|
[
{
"answer_id": 198118,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 1,
"selected": false,
"text": "<p>You can set the range for a chart dynamically in Excel. You can use something like the following VBA code to do it:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target as Range)\n Select Case Target \n Case Cells(14, 2)\n Sheet1.ChartObjects(1).Chart.SetSourceData Range(\"$C5:$C$\" & Cells(14,2))\n ...\n End Select\nEnd Sub\n</code></pre>\n\n<p>In this case, the cell containing the number of the last row to include is B14 (remember row first when referring to the Cells object). You could also use a variable instead of the Cells reference if you wanted to do this entirely in code. (This works in both 2007 and 2003.) You can assign this procedure to a button and click it to refresh your chart once you update the cell containing the last row.</p>\n\n<p>However, this may not be precisely what you want to do ... I am not aware of a way to use a formula directly within a chart to specify source data. </p>\n\n<p><strong>Edit:</strong> And as PConroy points out in a comment, you could put this code in the Change event for that worksheet, so that neither a button nor a key combination is necessary to run the code. You can also add code so that it updates each chart only when the matching cell is edited.</p>\n\n<p>I've updated the example above to reflect this. </p>\n"
},
{
"answer_id": 198143,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 1,
"selected": false,
"text": "<p>You could look at dynamic ranges. If you use the OFFSET function, you can specify a starting cell and the number of rows and columns to select. <a href=\"http://www.cpearson.com/excel/named.htm\" rel=\"nofollow noreferrer\">This site</a> has some useful information about assigning a name to an OFFSET range.</p>\n"
},
{
"answer_id": 198164,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 4,
"selected": true,
"text": "<p>OK, I had to do a little more research, here's how to make it work,\ncompletely within the spreadsheet (without VBA):</p>\n\n<p>Using A1 as the end of your desired range,\nand the chart being on the same sheet as the data: </p>\n\n<p>Name the first cell of the data (C5) as a named range, say TESTRANGE.<br>\nCreated a named range MYDATA as the following formula: </p>\n\n<p>=OFFSET(TESTRANGE, 0, 0, Sheet1!$A$1, 1) </p>\n\n<p>Now, go to the SERIES tab of the chart SOURCE DATA dialog,\nand change your VALUES statement to: </p>\n\n<p>=Sheet1!MYDATA</p>\n\n<p>Now everytime you change the A1 cell value, it'll change the chart. </p>\n\n<p>Thanks to Robert Mearns for catching the flaws in my previous answer.</p>\n"
},
{
"answer_id": 198724,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 1,
"selected": false,
"text": "<p>+1s for the name solution.</p>\n\n<p>Note that names don't really really reference ranges, they reference <strong>formulae</strong>. That's why you can set a name to something like \"=OFFSET(...)\" or \"=COUNT(...)\". You can create named constants, just make the name reference something like \"=42\".</p>\n\n<p>Named formulae and array formulae are the two worksheet techniques that I find myself applying to not-quite-power-user worksheets over and over again.</p>\n"
},
{
"answer_id": 199587,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 2,
"selected": false,
"text": "<p>This can be achieved in two steps:</p>\n\n<ul>\n<li>Create a dynamic named range</li>\n<li>Add some VBA code to update the charts data source to the named range</li>\n</ul>\n\n<h3>Create a dynamic named Range</h3>\n\n<p>Enter the number of rows in your data range into a cell on your data sheet.</p>\n\n<p>Create a named range on your data sheet (Insert - Name - Define) called <strong>MyRange</strong> that has a formula similar this:</p>\n\n<pre><code>=OFFSET(Sheet1!$A$1,0,0,Sheet1!$D$1,3)\n</code></pre>\n\n<p>Update the formula to match your layout</p>\n\n<ul>\n<li><em>Sheet1!$A$1</em> set this to the top left hand side of your data range</li>\n<li><em>Sheet1!$D$1</em> set this to the cell containing the number of rows</li>\n<li><em>3</em> set this value to the number of columns</li>\n</ul>\n\n<p>Test that the named range is working:</p>\n\n<p>Select the dropdown menus Edit - Go To, type <strong>MyRange</strong> into the reference field.\nYour data area for the chart should be selected.</p>\n\n<h3>Add some VBA code</h3>\n\n<p>Open the VBA IDE (Alt-F11)</p>\n\n<p>Select Sheet1 in the VBAProject window and insert this code</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n\n If Target.Address <> \"$D$1\" Then Exit Sub\n 'Change $D$1 to the cell where you have entered the number of rows\n 'When the sheet changes, code checks to see if the cell $D$1 has changed\n\n ThisWorkbook.Sheets(\"Sheet1\").ChartObjects(1).Chart.SetSourceData _\n Source:=ThisWorkbook.Sheets(\"Sheet1\").Range(\"MyRange\")\n ' ThisWorkbook.Sheets(\"Chart1\").SetSourceData _\n Source:=ThisWorkbook.Sheets(\"Sheet1\").Range(\"MyRange\")\n 'The first line of code assumes that chart is embedded into Sheet1\n 'The second line assumes that the chart is in its own chart sheet\n 'Uncomment and change as required\n\n 'Add more code here to update all the other charts\n\nEnd Sub\n</code></pre>\n\n<h3>Things to watch for</h3>\n\n<p>Do not directly use the named range as the data source for the chart. If you enter the named range \"MyRange\" as the Source Data - Data Range for the chart, Excel will automatically convert the named range into an actual range. Any future changes to your named range will therefore not update your chart.</p>\n\n<p>Performance might be impacted by the approaches listed above.</p>\n\n<p>The <strong>OFFSET</strong> function in the named range is \"volatile\" which means that it recalculates whenever any cell in the workbook calculates. If performance is an issue, replace it with the <strong>INDEX</strong> formula.</p>\n\n<pre><code>=Sheet1!$A$1:INDEX(Sheet1!$1:$65536,Sheet1!$D$1,2)\n</code></pre>\n\n<p>The code fires everytime data is changed on Sheet1. If performance is an issue, change the code to run only when requested (i.e. via a button or menu).</p>\n"
},
{
"answer_id": 1290364,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>An easy way to do this is to just hide the rows/columns you don't want included - when you go to the graph it automatically excludes the hidden rows/columns</p>\n"
},
{
"answer_id": 49717489,
"author": "Shai Alon",
"author_id": 1852977,
"author_profile": "https://Stackoverflow.com/users/1852977",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Enhancing the answer of @Robert Mearns</strong>, here's how to use dynamic cells ranges for graphs <strong><em>using only the Excel's formulas</em></strong> (no VBA required):</p>\n\n<p><strong>Create a dynamic named Range</strong></p>\n\n<p>Say you have 3 columns like:</p>\n\n<p>A5 | Time | Data1 | Data2 |</p>\n\n<p>A6 | 00:00 | 123123 | 234234 |</p>\n\n<p>...</p>\n\n<p>A3000 | 16:54 | 678678 | 987987 |</p>\n\n<p>Now, the range of your data may change according to the data you may have, like you have 20 rows of data, 3000 rows of data or even 25000 rows of data. You want to have a graph that will be updated automatically without the need to re-set the range of your data every time you update the data itself.</p>\n\n<p>Here's how to do it simply:</p>\n\n<ol>\n<li><p>Define another cell that it's value will have the number of the occupied cells with data, and put the formula <code>=COUNTIF(A:A,\"<>\"&\"\")</code> in it. <em>For example, this will be in cell</em> <strong><em>D1</em></strong>.</p></li>\n<li><p>Go to \"Formulas\" tab -> \"Define Name\" to define a name range.</p></li>\n<li><p>In the \"New Name\" window:</p>\n\n<p>i. Give your data range a name, <em>like</em> <strong><em>DataRange</em></strong> <em>for example.</em></p>\n\n<p>ii. In the \"Refers to\" set the formula to: <code>=OFFSET(Sheet1!$A$1, 0, 0,Sheet1!$D$1,3)</code>, </p>\n\n<p>where:</p>\n\n<ul>\n<li><p><code>Sheet1!$A$1</code> => Reference: is the Reference from which you want to base the offset.</p></li>\n<li><p><code>0</code> => Rows: is the number of rows, up or down, that you want the upper-left cell of the results to refer to.</p></li>\n<li><p><code>0</code> => Columns: is the number of columns, to the left or right, that you want the upper-left cell of the results to refer to.</p></li>\n<li><p><code>Sheet1!$D$1</code> => Height: is the height, in number of rows, that you want the result to be.</p></li>\n<li><p><code>3</code> => Width: is the width, in number of columns, that you want the result to be.</p></li>\n</ul></li>\n<li><p>Add a Graph, and in the \"Select Data Source\" window, in the Chart data range, insert the formula as you created. <em>For the example: <code>=Sheet1!DataRange</code></em></p></li>\n</ol>\n\n<p><strong>The Cons:</strong> If you directly use the named range as the data source for the chart, Excel will automatically convert the named range into an actual range. Any future changes to your named range will therefore not update your chart.</p>\n\n<p>For that you need to edit the chart and re-set the range to <code>=Sheet1!DataRange</code> every time. This may not be so usable, but it's better than editing the range manually...</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4014/"
] |
I've got a spreadsheet with plenty of graphs in it and one sheet with loads of data feeding those graphs.
I've plotted the data on each graph using
```
=Sheet1!$C5:$C$3000
```
This basically just plots the values in C5 to C3000 on a graph.
Regularly though I just want to look at a subset of the data i.e. I might just want to look at the first 1000 rows for example. Currently to do this I have to modify the formula in each of my graphs which takes time.
Would you know a way to simplify this? Ideally if I could just have a cell on single sheet that it reads in the row number from and plots all the graphs from C5 to C 'row number' would be best.
Any help would be much appreciated.
|
OK, I had to do a little more research, here's how to make it work,
completely within the spreadsheet (without VBA):
Using A1 as the end of your desired range,
and the chart being on the same sheet as the data:
Name the first cell of the data (C5) as a named range, say TESTRANGE.
Created a named range MYDATA as the following formula:
=OFFSET(TESTRANGE, 0, 0, Sheet1!$A$1, 1)
Now, go to the SERIES tab of the chart SOURCE DATA dialog,
and change your VALUES statement to:
=Sheet1!MYDATA
Now everytime you change the A1 cell value, it'll change the chart.
Thanks to Robert Mearns for catching the flaws in my previous answer.
|
198,049 |
<p>So I made some timers for a quiz. The thing is, I just realized when I put </p>
<pre><code>javascript: alert("blah");
</code></pre>
<p>in the address, the popup alert box <strong>pauses</strong> my timer. Which is very unwanted in a quiz.</p>
<p>I don't think there is any way to stop this behaviour... but I'll ask anyway.</p>
<p>If there is not, mind suggesting what should I do?</p>
|
[
{
"answer_id": 198056,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 3,
"selected": false,
"text": "<p>No, there is no way to prevent alert from stopping the single thread in JavaScript. Probably you can use some other way of user notification, for example a floating layer.</p>\n"
},
{
"answer_id": 198062,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 2,
"selected": false,
"text": "<p>It's modal and stops execution. Consider an alternative which does not pause execution like a Lightbox technique.</p>\n"
},
{
"answer_id": 198160,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 4,
"selected": true,
"text": "<p>Apparently the preview rendering differs from the posted rendering. This paragraph is here to make sure the next two lines show up as code.</p>\n\n<pre><code>// Preserve native alert() if you need it for something special\nwindow.nativeAlert = window.alert;\n\nwindow.alert = function(msg) {\n // Do something with msg here. I always write mine to console.log,\n // but then I have rarely found a use for a real modal dialog,\n // and most can be handled by the browser (like window.onbeforeunload).\n};\n</code></pre>\n"
},
{
"answer_id": 198172,
"author": "Mnebuerquo",
"author_id": 5114,
"author_profile": "https://Stackoverflow.com/users/5114",
"pm_score": 2,
"selected": false,
"text": "<p>I think the question asker is trying to prevent cheating. Since a user can type javascript: alert(\"paused\"); into the address bar, or make a bookmarklet to do that, it's easy to pause the quiz and cheat.</p>\n\n<p>The only thing I can think of is to use Date() to get the current time, and check it again when the timer fires. Then if the time difference is not reasonably close to the intended timer duration, show an admonishment and disqualify the answer to that question or let them flunk the quiz. There is no way to prevent the user from pausing your quiz, but it should be possible to catch them. </p>\n\n<p>Of course with any cheat-proofing, you motivate people to become better cheaters. A person could change the system time on their PC, and fool the javascript Date() constructor which gets the time from the operating system.</p>\n\n<p>You can use an interval to do a repeated clock comparison against a one second interval length. The interval handler can also update a time-remaining field on the user's display. Then the users can feel the pressure build as time runs out on their quiz. Fun times!</p>\n"
},
{
"answer_id": 198265,
"author": "Filini",
"author_id": 21162,
"author_profile": "https://Stackoverflow.com/users/21162",
"pm_score": 3,
"selected": false,
"text": "<p>Never, ever rely on javascript (or any other client-side time) to calculate elapsed times for operations done between postbacks, or different pages.</p>\n\n<p>If you always compare server dates, it will be hard for people to cheat:</p>\n\n<ol>\n<li>first page request, store the server time</li>\n<li>ping with javascript calls each N seconds, compare the 2 server times, and return the elapsed (just for show)</li>\n<li>when the user submits the form, compare the 2 server times, calculate the elapsed time, and discard the ones which took too long (ie: possible cheaters)</li>\n</ol>\n"
},
{
"answer_id": 198915,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 2,
"selected": false,
"text": "<p>The feedback loop on SyaZ's question has clarified the issues at stake.</p>\n\n<p>Here's an attempt to summarize the good answers so far:</p>\n\n<ul>\n<li><p>Client scripts are by nature are easy to manipulate to cheat an online quiz. SEE <a href=\"https://stackoverflow.com/questions/198049/prevent-js-alert-from-pausing-timers#198265\">@Filini 's Server-side approach</a></p></li>\n<li><p>window.alert = function(msg) {} will overriding <em>alert()</em> and perhaps defeat the low hanging fruit of putting in the addressbar: <em>javascript:alert('Pausing page so I can google the answer') or I'll use my Phone-A-Friend now.</em> <a href=\"https://stackoverflow.com/questions/198049/prevent-js-alert-from-pausing-timers#198160\">Courtesy of @eyelidlessness</a></p></li>\n<li><p>If you must use a client-side approach, instead of using setTimeOut(), you could use a custom date-compare-based pause function like this (<a href=\"https://stackoverflow.com/questions/198049/prevent-js-alert-from-pausing-timers#198172\">concept by @Mnebuerquo</a>, code example by me (<a href=\"https://stackoverflow.com/users/11181/micahwittman\">@micahwittman</a>)):</p></li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>var beginDate = new Date();\n\nfunction myTimeout(milsecs){\n do { curDate = new Date(); }\n while((curDate-beginDate) < milsecs);\n}\n\nfunction putDownYourPencils(milsecs){\n myTimeout(milsecs);\n var seconds = milsecs / 1000;\n alert('Your ' + seconds + ' seconds are up. Quiz is over.');\n}\n\nputDownYourPencils(3000);\n</code></pre>\n"
},
{
"answer_id": 199343,
"author": "Christopher Parker",
"author_id": 27583,
"author_profile": "https://Stackoverflow.com/users/27583",
"pm_score": 2,
"selected": false,
"text": "<p>Ultimately, you cannot trust user input. Without keeping track of the time elapsed on the server, there's just no guarantee the data hasn't been manipulated.</p>\n\n<p>However, if you're confident your quiz-takers aren't JavaScript-savvy, and are merely relying on a \"trick\" they found somewhere, you could test for cheating (pausing) with the following code, which doesn't require modifying window.alert:</p>\n\n<pre><code>var timer = {\n startDatetime: null,\n startSec: 0,\n variance: 1,\n exitOnPause: true,\n count: function (config) {\n var that = this;\n\n if (typeof config == \"object\" && typeof parseInt(config.seconds) == \"number\" && !isNaN(parseInt(config.seconds)))\n {\n if (typeof parseFloat(config.variance) == \"number\" && !isNaN(parseFloat(config.variance))) this.variance = config.variance;\n if (typeof config.exitOnPause == \"boolean\") this.exitOnPause = config.exitOnPause;\n\n if (config.seconds > 0)\n {\n if (!this.startSec) this.startSec = config.seconds;\n if (!this.startDatetime) this.startDatetime = new Date();\n var currentDatetime = new Date();\n\n if (currentDatetime.getTime() - this.startDatetime.getTime() > (this.startSec - config.seconds) * this.variance * 1000)\n {\n if (typeof config.onPause == \"function\") config.onPause();\n\n if (!this.exitOnPause)\n {\n this.startDatetime = new Date();\n this.startSec = config.seconds--;\n window.setTimeout(function () { that.count(config); }, 1000);\n }\n }\n else\n {\n config.seconds--;\n window.setTimeout(function () { that.count(config); }, 1000);\n }\n }\n else\n {\n if (typeof config.onFinish == \"function\") config.onFinish();\n }\n }\n }\n};\n</code></pre>\n\n<p>This timer object has a single method, count(), which accepts an object as input. It expects a seconds property in the input object at minimum.</p>\n\n<p>For some reason, window.setTimeout doesn't always work as expected. Sometimes, on my machine, window.setTimeout(x, 1000), which should execute the code after 1 second, took more than 2 seconds. So, in a case like this, you should allow a variance, so people who aren't cheating don't get flagged as cheaters. The variance defaults to 1, but it can be overridden in the input object. Here's an example of how to use this code, which allows 2.5 seconds of \"wiggle room\" for slow-pokes:</p>\n\n<pre><code>timer.count({\n seconds: 10,\n onPause: function () { alert(\"You cheated!\"); window.location.replace(\"cheatersAreBad.html\"); },\n onFinish: function () { alert(\"Time's up!\"); },\n variance: 2.5\n});\n</code></pre>\n\n<p>With a solution like this, you could use Ajax to tell a server-side script that the user has paused the timer or redirect the user to a page explaining they were caught cheating, for example. If, for some reason, you wanted to allow the user to continue taking the quiz after they've been caught cheating, you could set exitOnPause to false:</p>\n\n<pre><code>timer.count({\n seconds: 10,\n exitOnPause: false,\n onPause: function () { recordCheaterViaAjax(); },\n onFinish: function () { alert(\"Time's up!\"); },\n variance: 2.5\n});\n</code></pre>\n"
},
{
"answer_id": 11213519,
"author": "sroll",
"author_id": 1483632,
"author_profile": "https://Stackoverflow.com/users/1483632",
"pm_score": 0,
"selected": false,
"text": "<p>The server session could be set to expire at say 1 hour. The javascript could be used as only a display tool for the user to know how much time is left. If he decides to cheat by pausing the timer, then he might be suprised when posting his test that his session has timed out.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15345/"
] |
So I made some timers for a quiz. The thing is, I just realized when I put
```
javascript: alert("blah");
```
in the address, the popup alert box **pauses** my timer. Which is very unwanted in a quiz.
I don't think there is any way to stop this behaviour... but I'll ask anyway.
If there is not, mind suggesting what should I do?
|
Apparently the preview rendering differs from the posted rendering. This paragraph is here to make sure the next two lines show up as code.
```
// Preserve native alert() if you need it for something special
window.nativeAlert = window.alert;
window.alert = function(msg) {
// Do something with msg here. I always write mine to console.log,
// but then I have rarely found a use for a real modal dialog,
// and most can be handled by the browser (like window.onbeforeunload).
};
```
|
198,051 |
<p>I was always wondering if there is operator for deleting multi dimensional arrays in the standard C++ language.</p>
<p>If we have created a pointer to a single dimensional array</p>
<pre><code>int *array = new int[size];
</code></pre>
<p>the delete looks like:</p>
<pre><code>delete [] array;
</code></pre>
<p>That's great. But if we have two dimension array, we can not do</p>
<pre><code>delete [][] twoDimenstionalArray;
</code></pre>
<p>Instead, we should loop and delete the items, like in <a href="http://eli.thegreenplace.net/2003/07/23/allocating-multi-dimensional-arrays-in-c/" rel="noreferrer">this</a> example.</p>
<p>Can anybody explain why?</p>
|
[
{
"answer_id": 198059,
"author": "Dan Hewett",
"author_id": 17975,
"author_profile": "https://Stackoverflow.com/users/17975",
"pm_score": 0,
"selected": false,
"text": "<p>delete[] applies to any non-scalar (array).</p>\n"
},
{
"answer_id": 198064,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 2,
"selected": false,
"text": "<p>not sure of the exact reason from a language design perspective, I' guessing it has something to do with that fact that when allocating memory you are creating an array of arrays and each one needs to be deleted. </p>\n\n<pre><code>int ** mArr = new int*[10];\nfor(int i=0;i<10;i++)\n{\n mArr[i]=new int[10];\n}\n</code></pre>\n\n<p>my c++ is rusty, I'm not sure if thats syntactically correct, but I think its close.</p>\n"
},
{
"answer_id": 198065,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 6,
"selected": true,
"text": "<p>Technically, there aren't two dimensional arrays in C++. What you're using as a two dimensional array is a one dimensional array with each element being a one dimensional array. Since it doesn't technically exist, C++ can't delete it.</p>\n"
},
{
"answer_id": 198069,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 3,
"selected": false,
"text": "<p>The reason delete is called multiple times in that example is because new is called multiple times too. Delete must be called for each new.</p>\n\n<p>For example if I allocate 1,000,000 bytes of memory I cannot later delete the entries from 200,000 - 300,00, it was allocated as one whole chunk and must be freed as one whole chunk.</p>\n"
},
{
"answer_id": 198070,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 4,
"selected": false,
"text": "<p>Because there is no way to call</p>\n\n<pre><code>int **array = new int[dim1][dim2];\n</code></pre>\n\n<p>All news/deletes must be balanced, so there's no point to a <code>delete [][]</code> operator.</p>\n\n<p><code>new int[dim1][dim2]</code> returns a pointer to an array of size <code>dim1</code> of type <code>int[dim2]</code>. So <code>dim2</code> must be a compile time constant. This is similar to allocating multi-dimensional arrays on the stack.</p>\n"
},
{
"answer_id": 198105,
"author": "James Rose",
"author_id": 9703,
"author_profile": "https://Stackoverflow.com/users/9703",
"pm_score": 3,
"selected": false,
"text": "<p>The reason you have to loop, like in the example you mention, is that the number of arrays that needs to be deleted is not known to the compiler / allocator. </p>\n\n<p>When you allocated your two-dimensional array, you really created N one-dimensional arrays. Now each of those have to be deleted, but the system does not know how many of them there are. The size of the top-level array, i.e. the array of pointers to your second-level arrays, is just like any other array in C: its size is not stored by the system.</p>\n\n<p>Therefore, there is no way to implement <code>delete [][]</code> as you describe (without changing the language significantly).</p>\n"
},
{
"answer_id": 198502,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a wrapper class to do all those things for you.\nWorking with \"primitive\" data types usually is not a good solution (the arrays should be encapsulated in a class). For example std::vector is a very good example that does this.</p>\n\n<p>Delete should be called exactly how many times new is called. Because you cannot call \"a = new X[a][b]\" you cannot also call \"delete [][]a\".</p>\n\n<p>Technically it's a good design decision preventing the appearance of weird initialization of an entire n-dimensional matrix.</p>\n"
},
{
"answer_id": 200133,
"author": "user27732",
"author_id": 27732,
"author_profile": "https://Stackoverflow.com/users/27732",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I think it is easy to implement, but too dangerous. It is easy to tell whether a pointer is created by <code>new[]</code>, but hard to tell about <code>new[]...[]</code>(if allowed).</p>\n"
},
{
"answer_id": 5784429,
"author": "Adam",
"author_id": 686534,
"author_profile": "https://Stackoverflow.com/users/686534",
"pm_score": 2,
"selected": false,
"text": "<p>While all these answers are relevant, I will try to explain what came to an expectation, that something like <em><code>delete[][] array;</code></em> may work on dynamically allocated arrays and why it's not possible:</p>\n\n<p>The syntax <code>int array[ROWS][COLS];</code> allowed on <strong>statically</strong> allocated arrays is just abstraction for programmers, which in reality creates one-dimensional array <code>int array[ROWS*COLS];</code>. But during compilation process (when dimension sizes <code>COLS</code> and <code>ROWS</code> must be constants by standard) the compiler also remembers the size of those dimensions, that are necessary to later address elements using syntax e.g. <code>array[x][y] = 45</code>. Compiler, being known of this size, will then replace <code>[x][y]</code> with the corresponding index to one-dimensional array using simple math: <code>[COLS*x + y]</code>.</p>\n\n<p>On the other hand, this is not the case with <strong>dynamically</strong> allocated arrays, if you want the same multi-dimensional functionality (in fact notation). As their size can be determined during runtime, they would have to remember the size of each additional dimension for later usage as well - and remember that for the whole life of the array. Moreover, system changes would have to be implemented here to work with arrays actually as multi-dimensional, leaving the form of <code>[x][y]</code> access notation in the code, not replacing it with an one-dimensional notation during compilation, but later replacing it within runtime.</p>\n\n<p>Therefore an <strong>absence</strong> of <em><code>array = new int[ROWS][COLS]</code></em> implies no necessity for <em><code>delete[][] array;</code></em>. And as already mentioned, it can't be used on your example to delete your \"multi-dimensional\" array, because your sub-arrays (additional dimensions) are allocated separately (using separate <code>new</code> call), so they are independent of the top array (<code>array_2D</code>) which contains them and they all can't be deleted at once.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446104/"
] |
I was always wondering if there is operator for deleting multi dimensional arrays in the standard C++ language.
If we have created a pointer to a single dimensional array
```
int *array = new int[size];
```
the delete looks like:
```
delete [] array;
```
That's great. But if we have two dimension array, we can not do
```
delete [][] twoDimenstionalArray;
```
Instead, we should loop and delete the items, like in [this](http://eli.thegreenplace.net/2003/07/23/allocating-multi-dimensional-arrays-in-c/) example.
Can anybody explain why?
|
Technically, there aren't two dimensional arrays in C++. What you're using as a two dimensional array is a one dimensional array with each element being a one dimensional array. Since it doesn't technically exist, C++ can't delete it.
|
198,058 |
<p>I'd like to show a div that has a background-color with the height and width set to 100% but no content. Is it possible to do that without putting a &nbsp; inside?</p>
<p>Edit: Thanks to Mark Biek for pointing out that empty div with width and height styles shows how I'd expect. My div is in a table cell, where it does not show.</p>
<pre><code><table style="width:100%">
<tr>
<th>Header</th>
<td><div id="foo"></div></td>
</tr>
</table>
</code></pre>
|
[
{
"answer_id": 198083,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": true,
"text": "<p>This seems to work in Firefox, Safari, IE6, & IE7.</p>\n\n<pre><code><html>\n <head>\n <style>\n #foo{\n background: #ff0000;\n width: 100%;\n height: 100%;\n border: 2px dashed black;\n }\n </style>\n </head>\n <body onload=\"\">\n <div id=\"foo\"></div>\n </body>\n</html>\n</code></pre>\n\n<p><a href=\"http://farm4.static.flickr.com/3008/2938703792_886e488f68_o.png\" rel=\"nofollow noreferrer\"><img src=\"https://farm4.static.flickr.com/3008/2938703792_f4602930fb_m.jpg\" alt=\"3 Browser example\" /></a></p>\n"
},
{
"answer_id": 198084,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 0,
"selected": false,
"text": "<p>I think it depends on the browser (IE/Gecko engine/Webkit engine) and on the mode (Standards mode, Quirks mode). I had some divs appearing in FFox/Standards mode and not appearing in IE6/7.</p>\n\n<p>You probably can do it in a cross browser way with only css, but you'll probably resort to some css hacks.</p>\n"
},
{
"answer_id": 198098,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 2,
"selected": false,
"text": "<p>Hmmm... I'm not sure what exactly the specs say, but I know that while empty inline-elements (e.g. span) are valid, empty block-elements (e.g. p or div) get \"cleaned up\" by html-tidy.</p>\n\n<p>Thus I'd say it's safer to stick to the &nbsp; as it does no harm in your case. I'd also add a comment like \"<!-- background container -->\" or something like that. So everyone who's going to change your html knows that the div has a special meaning even though it's empty.</p>\n"
},
{
"answer_id": 198100,
"author": "Chris Serra",
"author_id": 13435,
"author_profile": "https://Stackoverflow.com/users/13435",
"pm_score": 0,
"selected": false,
"text": "<p>From experience, IE won't render borders of empty elements (at least empty <td> elements)</p>\n"
},
{
"answer_id": 198145,
"author": "tomjedrz",
"author_id": 9852,
"author_profile": "https://Stackoverflow.com/users/9852",
"pm_score": 2,
"selected": false,
"text": "<p>IMHO you should include the nbsp for otherwise empty DIVs if you want them to actually render into something. </p>\n\n<p>On a \"theoretical\" note .. the browser is not <strong>supposed</strong> to show anything if there is no content. The entire point of nbsp is to indicate empty space. This is both common sense and (I believe) the standard.</p>\n\n<p>On a practical side .. are you have three choices. One is to leave nbsp off, knowing that you will get unpredictable results. This is likely the easiest to code. Another is to always include nbsp, either by always putting nbsp at the end of the div or testing for empty and adding nbsp if it is empty. The third it to test for the browser and insert nbsp when needed. </p>\n"
},
{
"answer_id": 202707,
"author": "GameFreak",
"author_id": 26659,
"author_profile": "https://Stackoverflow.com/users/26659",
"pm_score": 0,
"selected": false,
"text": "<p>perhaps</p>\n\n<p><code>#foo {empty-cells: show;}</code></p>\n\n<p>although that may be only for <code><td></code></p>\n"
},
{
"answer_id": 540184,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You should include <code>&nbsp;</code> at all times.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23427/"
] |
I'd like to show a div that has a background-color with the height and width set to 100% but no content. Is it possible to do that without putting a inside?
Edit: Thanks to Mark Biek for pointing out that empty div with width and height styles shows how I'd expect. My div is in a table cell, where it does not show.
```
<table style="width:100%">
<tr>
<th>Header</th>
<td><div id="foo"></div></td>
</tr>
</table>
```
|
This seems to work in Firefox, Safari, IE6, & IE7.
```
<html>
<head>
<style>
#foo{
background: #ff0000;
width: 100%;
height: 100%;
border: 2px dashed black;
}
</style>
</head>
<body onload="">
<div id="foo"></div>
</body>
</html>
```
[](http://farm4.static.flickr.com/3008/2938703792_886e488f68_o.png)
|
198,071 |
<p>Greetings!</p>
<p>I am trying to check directory write-permissions from within a Windows MFC/ATL program using C++. My first guess is to use the C-standard _access function, e.g.:</p>
<pre><code>if (_access("C:\mydir", 2) == -1)
// Directory is not writable.
</code></pre>
<p>But apparently on Windows 2000 and XP, _access can't determine directory permissions. (i.e. the Security tab in the Properties dialog when you right-click on a directory in Explorer) So, is there an elegant way to determine a directory's write-permissions in Windows 2000/XP using any of the Windows C++ libraries? If so, how?</p>
<p>Thanks</p>
<p>Evan</p>
|
[
{
"answer_id": 198092,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Use sec api.\nYou can ask on Adv. Win32 api newsgroup :\nnews://194.177.96.26/comp.os.ms-windows.programmer.win32\nwhere it has often been discussed (C/C++ code)</p>\n"
},
{
"answer_id": 198162,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 3,
"selected": true,
"text": "<p>You can call CreateFile with GENERIC_WRITE access to check this.\n<a href=\"http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx</a></p>\n\n<p>It's not a C++ library but it still counts as elegant because it directly does what you want...</p>\n"
},
{
"answer_id": 198317,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 1,
"selected": false,
"text": "<p>There are many <a href=\"http://msdn.microsoft.com/en-us/library/aa375742(VS.85).aspx\" rel=\"nofollow noreferrer\">Windows security functions</a>, although I wouldn't call their usage particularly elegant. I would recommend GetNamedSecurityInfo as a general solution, but the CreateFile solution has a certain simplicity and directness which I can also appreciate. :)</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27493/"
] |
Greetings!
I am trying to check directory write-permissions from within a Windows MFC/ATL program using C++. My first guess is to use the C-standard \_access function, e.g.:
```
if (_access("C:\mydir", 2) == -1)
// Directory is not writable.
```
But apparently on Windows 2000 and XP, \_access can't determine directory permissions. (i.e. the Security tab in the Properties dialog when you right-click on a directory in Explorer) So, is there an elegant way to determine a directory's write-permissions in Windows 2000/XP using any of the Windows C++ libraries? If so, how?
Thanks
Evan
|
You can call CreateFile with GENERIC\_WRITE access to check this.
<http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx>
It's not a C++ library but it still counts as elegant because it directly does what you want...
|
198,082 |
<p>How to find out size of session in ASP.NET from web application?</p>
|
[
{
"answer_id": 198158,
"author": "Rafe",
"author_id": 27497,
"author_profile": "https://Stackoverflow.com/users/27497",
"pm_score": 0,
"selected": false,
"text": "<p>I think you can find that information by adding <strong>Trace=\"true\"</strong> to the page directive of a aspx page. Then when the page loads you can see a large number of details regarding the page request, including session information i think.</p>\n\n<p>You can also enable tracing in your entire application by adding a line to your web.config file. Something like:</p>\n\n<pre><code><trace enabled=\"true\" requestLimit=\"10\" pageOutput=\"true\" traceMode=\"SortByTime\" \n localOnly=\"true\"/>\n</code></pre>\n"
},
{
"answer_id": 198386,
"author": "ddc0660",
"author_id": 16027,
"author_profile": "https://Stackoverflow.com/users/16027",
"pm_score": 6,
"selected": true,
"text": "<p>If you're trying to get the size of Session during runtime rather than in debug tracing, you might want to try something like this:</p>\n\n<pre><code>long totalSessionBytes = 0;\nBinaryFormatter b = new BinaryFormatter();\nMemoryStream m;\nforeach(var obj in Session) \n{\n m = new MemoryStream();\n b.Serialize(m, obj);\n totalSessionBytes += m.Length;\n}\n</code></pre>\n\n<p>(Inspired by <a href=\"http://www.codeproject.com/KB/session/exploresessionandcache.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/session/exploresessionandcache.aspx</a>)</p>\n"
},
{
"answer_id": 5330435,
"author": "David",
"author_id": 663115,
"author_profile": "https://Stackoverflow.com/users/663115",
"pm_score": 5,
"selected": false,
"text": "<p>The code in the answer above kept giving me the same number. Here is the code that finally worked for me:</p>\n\n<pre><code>private void ShowSessionSize()\n{\n Page.Trace.Write(\"Session Trace Info\");\n\n long totalSessionBytes = 0;\n System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = \n new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();\n System.IO.MemoryStream m;\n foreach (string key in Session)\n {\n var obj = Session[key];\n m = new System.IO.MemoryStream();\n b.Serialize(m, obj);\n totalSessionBytes += m.Length;\n\n Page.Trace.Write(String.Format(\"{0}: {1:n} kb\", key, m.Length / 1024));\n }\n\n Page.Trace.Write(String.Format(\"Total Size of Session Data: {0:n} kb\", \n totalSessionBytes / 1024));\n}\n</code></pre>\n"
},
{
"answer_id": 64385604,
"author": "cederlof",
"author_id": 198953,
"author_profile": "https://Stackoverflow.com/users/198953",
"pm_score": 0,
"selected": false,
"text": "<p>This is my code for getting all current Session variables with its size in kB into a Dictionary.</p>\n<pre><code>// <KEY, SIZE(kB)>\nvar dict = new Dictionary<string, decimal>();\n\nBinaryFormatter b = new BinaryFormatter();\nMemoryStream m;\nforeach(string key in Session.Keys) \n{\n var obj = Session[key];\n if (obj == null)\n {\n dict.Add(key, -1);\n }\n else\n {\n m = new MemoryStream();\n b.Serialize(m, obj);\n \n //save the key and size in kB (rounded to two decimals)\n dict.Add(key, Math.Round(Convert.ToDecimal(m.Length) / 1024, 2)); \n }\n}\n\n//return dict\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23280/"
] |
How to find out size of session in ASP.NET from web application?
|
If you're trying to get the size of Session during runtime rather than in debug tracing, you might want to try something like this:
```
long totalSessionBytes = 0;
BinaryFormatter b = new BinaryFormatter();
MemoryStream m;
foreach(var obj in Session)
{
m = new MemoryStream();
b.Serialize(m, obj);
totalSessionBytes += m.Length;
}
```
(Inspired by <http://www.codeproject.com/KB/session/exploresessionandcache.aspx>)
|
198,087 |
<p>
We recently switched our Windows software packages from RPM (cygwin) to MSI (wix). Having a native packaging is a much welcome change and we intend to stick with it. However, MSI feels overly complicated for what it does and doesn't seem to provide some basic abilities. But I'm probably mistaken.
</p>
<p>
Is there a way to list all installed MSI from the command line ?
</p>
|
[
{
"answer_id": 198130,
"author": "Node",
"author_id": 7190,
"author_profile": "https://Stackoverflow.com/users/7190",
"pm_score": 5,
"selected": true,
"text": "<p>Mabybe <a href=\"http://msdn.microsoft.com/en-us/library/aa394378(VS.85).aspx\" rel=\"noreferrer\">this</a> is a good starting point for you example VB Script from MSDN:</p>\n\n<pre><code>strComputer = \".\"\n\nSet objWMIService = GetObject(\"winmgmts:\" & _\n \"{impersonationLevel=impersonate}!\\\\\" & _\n strComputer & _\n \"\\root\\cimv2\")\n\nSet colSoftware = objWMIService.ExecQuery _\n (\"SELECT * FROM Win32_Product\") \n\nIf colSoftware.Count > 0 Then\n\n Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n Set objTextFile = objFSO.CreateTextFile( _\n \"c:\\SoftwareList.txt\", True)\n\n For Each objSoftware in colSoftware\n objTextFile.WriteLine objSoftware.Caption & vbtab & _\n objSoftware.Version\n Next\n\n objTextFile.Close\n\nElse\n WScript.Echo \"Cannot retrieve software from this computer.\"\n\nEnd If\n</code></pre>\n"
},
{
"answer_id": 198185,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure if this is what you need but you can query the uninstall list from the command line with:</p>\n\n<pre><code>REG QUERY HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\n</code></pre>\n"
},
{
"answer_id": 13498298,
"author": "knut",
"author_id": 93360,
"author_profile": "https://Stackoverflow.com/users/93360",
"pm_score": 4,
"selected": false,
"text": "<p>You may use <a href=\"http://en.wikipedia.org/wiki/Powershell\" rel=\"noreferrer\">PowerShell</a> and <a href=\"http://en.wikipedia.org/wiki/Windows_Management_Instrumentation\" rel=\"noreferrer\">Windows Management Instrumentation (WMI)</a>. Here is a one liner:</p>\n\n<pre><code>Get-WmiObject -Class win32_product\n</code></pre>\n\n<p>Here is help for the <code>Get-WmiObject</code> <a href=\"http://en.wikipedia.org/wiki/Cmdlet\" rel=\"noreferrer\">cmdlet</a>:</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/dd315295.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/dd315295.aspx</a></p>\n\n<p>Here is a sample where we select the first installed program and format it as a table:</p>\n\n<pre><code>PS C:\\Users\\knut> Get-WmiObject -Class win32_product |\n>> select -First 1 | ft Name, Version, Vendor -AutoSize\n>>\n\nName Version Vendor\n---- ------- ------\nAWS SDK for .NET 1.2.0200 Amazon Web Services Developer Relations\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11892/"
] |
We recently switched our Windows software packages from RPM (cygwin) to MSI (wix). Having a native packaging is a much welcome change and we intend to stick with it. However, MSI feels overly complicated for what it does and doesn't seem to provide some basic abilities. But I'm probably mistaken.
Is there a way to list all installed MSI from the command line ?
|
Mabybe [this](http://msdn.microsoft.com/en-us/library/aa394378(VS.85).aspx) is a good starting point for you example VB Script from MSDN:
```
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & _
strComputer & _
"\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
("SELECT * FROM Win32_Product")
If colSoftware.Count > 0 Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile( _
"c:\SoftwareList.txt", True)
For Each objSoftware in colSoftware
objTextFile.WriteLine objSoftware.Caption & vbtab & _
objSoftware.Version
Next
objTextFile.Close
Else
WScript.Echo "Cannot retrieve software from this computer."
End If
```
|
198,114 |
<p>To do an unattended installation of any MSI package, one can simply use the following command:</p>
<pre><code>msiexec /qn /i package.msi
</code></pre>
<p>However, this triggers an asynchronous installation: if you happen to chain 2 dependent installations, you will have to wait somehow for the 1st installation to complete.</p>
<p>Is there a way to do this from the command line ?</p>
|
[
{
"answer_id": 198121,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 2,
"selected": false,
"text": "<p>We'd run into this a number of times with various products and I'd ended up using a small outer program that launches each msi and waits until it finishes to start the next one. You can probably do this in something as lightweight as a vbscript, but at the time we wanted a bit more gui so we had a larger outer program.</p>\n"
},
{
"answer_id": 13939918,
"author": "Ben Mosher",
"author_id": 344143,
"author_profile": "https://Stackoverflow.com/users/344143",
"pm_score": 3,
"selected": false,
"text": "<p>I've had luck with this:</p>\n\n<pre><code>start /wait msiexec /i MyInstaller.msi ...\n</code></pre>\n\n<p>Found in <a href=\"http://blogs.msdn.com/b/heaths/archive/2005/11/15/493236.aspx\">this blog post</a> from 2005. Hope you found it way back in '08.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11892/"
] |
To do an unattended installation of any MSI package, one can simply use the following command:
```
msiexec /qn /i package.msi
```
However, this triggers an asynchronous installation: if you happen to chain 2 dependent installations, you will have to wait somehow for the 1st installation to complete.
Is there a way to do this from the command line ?
|
I've had luck with this:
```
start /wait msiexec /i MyInstaller.msi ...
```
Found in [this blog post](http://blogs.msdn.com/b/heaths/archive/2005/11/15/493236.aspx) from 2005. Hope you found it way back in '08.
|
198,119 |
<p>I have a flash project that I'm trying to export as a single SWF. There's a main SWF file that loads about 6 other SWFs, and both the main and the child SWFs reference other external assets (images, sounds, etc). I'd like to package everything as a single .swf file so I don't have to tote the other assets around with the .swf. </p>
<p>All the coding is done in the timeline, but the assets haven't been imported into the Flash Authoring environment and I don't have time to do that right now (there are too many references to them everywhere). I'm hoping that there's just an option I'm missing that allows this sort of packaged export, but I haven't found anything like that.</p>
<p>I don't have access to Flex or mxmlc (and as the AS is timeline-based, they wouldn't necessarily help me). Any thoughts?</p>
<p>Thanks!</p>
<p>PS...if there's no way of doing exactly what I'm saying, I could deal with having all the assets in a "assets" folder or something like that, so I'd just be toting around main.swf and an assets folder. The problem here is that all the references to the assets assume that they're in the same folder as the main.swf file, so everything's assumed to be local...is there a way to change the scope of all external references in Flash (so, for example, all local references in the code are actually searched in /assets)?</p>
|
[
{
"answer_id": 198149,
"author": "Rafe",
"author_id": 27497,
"author_profile": "https://Stackoverflow.com/users/27497",
"pm_score": -1,
"selected": false,
"text": "<p>HI Justin,</p>\n\n<p>It sounds like you need to look into using shared libraries. Check out:</p>\n\n<p><a href=\"http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14767\" rel=\"nofollow noreferrer\">http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14767</a></p>\n"
},
{
"answer_id": 1413991,
"author": "nikaji",
"author_id": 171185,
"author_profile": "https://Stackoverflow.com/users/171185",
"pm_score": 2,
"selected": false,
"text": "<p>You <em>might</em> be able to decompile your swfs into XML with swfmill/mtasc and use a fancy XSLT to recombine them and recompile with swfmill/mtasc.</p>\n\n<p>If that doesn't work and if you're using MovieClip.loadMovie or MovieClipLoader.loadMovie you can overload their methods and intercept the url:</p>\n\n<pre><code>var realLoadMovie:Function = MovieClip.prototype.loadMovie;\n\nMovieClip.prototype.loadMovie = function(url:String, method:String) {\n return realLoadMovie(\"assets/\" + url, method);\n}\n\nvar test:MovieClip = createEmptyMovieClip(\"testclip\", getNextHighestDepth());\ntest.loadMovie(\"test.swf\");\n</code></pre>\n\n<p>You'll need to do some additional string parsing if the urls have a resource-type prefix such as file://</p>\n"
},
{
"answer_id": 2660483,
"author": "Juan Pablo Califano",
"author_id": 24170,
"author_profile": "https://Stackoverflow.com/users/24170",
"pm_score": 0,
"selected": false,
"text": "<p>There's a base parameter you can add when you embed the swf, just like align, scale, etc. If base is set, all relative urls will be prefixed with whatever path you define (well, almost all; videos and file reference objects being the exception here).\nOther than that, I'd go with nikaji's solution.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a flash project that I'm trying to export as a single SWF. There's a main SWF file that loads about 6 other SWFs, and both the main and the child SWFs reference other external assets (images, sounds, etc). I'd like to package everything as a single .swf file so I don't have to tote the other assets around with the .swf.
All the coding is done in the timeline, but the assets haven't been imported into the Flash Authoring environment and I don't have time to do that right now (there are too many references to them everywhere). I'm hoping that there's just an option I'm missing that allows this sort of packaged export, but I haven't found anything like that.
I don't have access to Flex or mxmlc (and as the AS is timeline-based, they wouldn't necessarily help me). Any thoughts?
Thanks!
PS...if there's no way of doing exactly what I'm saying, I could deal with having all the assets in a "assets" folder or something like that, so I'd just be toting around main.swf and an assets folder. The problem here is that all the references to the assets assume that they're in the same folder as the main.swf file, so everything's assumed to be local...is there a way to change the scope of all external references in Flash (so, for example, all local references in the code are actually searched in /assets)?
|
You *might* be able to decompile your swfs into XML with swfmill/mtasc and use a fancy XSLT to recombine them and recompile with swfmill/mtasc.
If that doesn't work and if you're using MovieClip.loadMovie or MovieClipLoader.loadMovie you can overload their methods and intercept the url:
```
var realLoadMovie:Function = MovieClip.prototype.loadMovie;
MovieClip.prototype.loadMovie = function(url:String, method:String) {
return realLoadMovie("assets/" + url, method);
}
var test:MovieClip = createEmptyMovieClip("testclip", getNextHighestDepth());
test.loadMovie("test.swf");
```
You'll need to do some additional string parsing if the urls have a resource-type prefix such as file://
|
198,135 |
<p>Which is faster? someCondition has the same probability of being true as it has of being false.</p>
<p>Insertion:</p>
<pre><code>arrayList = Array("apple", "pear","grape")
if someCondition then
' insert "banana" element
end if
</code></pre>
<p>Deletion:</p>
<pre><code>arrayList = Array("apple","banana","pear","grape")
if not someCondition then
' remove "banana" element
end if
</code></pre>
<p>It looks like it depends purely on the implementation of Insert and Remove. So which, in general, is faster? I'm leaning toward insertion because I've read that one can use CopyMemory to insert without looping. Is this the same for deletion? Does anyone have an example?</p>
<p>Edit:
This is VB6, not VB.NET.
For display reasons, I have to use insert rather than append.</p>
|
[
{
"answer_id": 198144,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>I've found an example showing that one can delete without looping as well. It looks simpler than the code to insert.</p>\n\n<pre><code>Public Sub RemoveArrayElement_Str(AryVar() As String, ByVal _\n RemoveWhich As Long)\n '// The size of the array elements\n '// In the case of string arrays, they are\n '// simply 32 bit pointers to BSTR's.\n Dim byteLen As Byte\n\n '// String pointers are 4 bytes\n byteLen = 4\n\n '// The copymemory operation is not necessary unless\n '// we are working with an array element that is not\n '// at the end of the array\n If RemoveWhich < UBound(AryVar) Then\n '// Copy the block of string pointers starting at\n ' the position after the\n '// removed item back one spot.\n CopyMemory ByVal VarPtr(AryVar(RemoveWhich)), ByVal _\n VarPtr(AryVar(RemoveWhich + 1)), (byteLen) * _\n (UBound(AryVar) - RemoveWhich)\n End If\n\n '// If we are removing the last array element\n '// just deinitialize the array\n '// otherwise chop the array down by one.\n If UBound(AryVar) = LBound(AryVar) Then\n Erase AryVar\n Else\n ReDim Preserve AryVar(UBound(AryVar) - 1)\n End If\nEnd Sub\n</code></pre>\n\n<p><a href=\"http://www.vb-helper.com/howto_delete_from_array.html\" rel=\"nofollow noreferrer\">http://www.vb-helper.com/howto_delete_from_array.html</a></p>\n"
},
{
"answer_id": 198146,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>I'd have to guess insert, because it can always just append whereas with the delete you have to worry about holes.</p>\n\n<p>But what version of vb? If you're in .Net and doing deletes or inserts, you shouldn't be using an array for this at all.</p>\n"
},
{
"answer_id": 198178,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 1,
"selected": false,
"text": "<p>Both have about the same performance because both require creating a new Array. Arrays are fixed size continuous structures. </p>\n\n<p>In order to maintain this on an insert a new Array must be created with an additional element. All of the existing values are copied into the array in their new position and then the inserted element is added. </p>\n\n<p>In order to maintain this for a delete a new Array must be created with one less element. Then all of the existing entries except for the delete must be copied into the new array. </p>\n\n<p>Both of these operations have essentially the same operations over nearly identical sizes. Performance won't be significantly different.</p>\n"
},
{
"answer_id": 198181,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": true,
"text": "<p>For a delete, every item after the removed item must be shifted down.</p>\n\n<p>For an Insert, space must be found for the new item. If there is empty space after the array that it can annex, then this takes no time, and the only time spend is more each item after the new item up, to make room in the middle.</p>\n\n<p>If there is no available space locally, a whole new array must be allocated and every item copied.</p>\n\n<p>So, when considering adding or deleting to the same array position, inserting could be as fast as deleting, but it maybe much longer. Inserting won't be faster.</p>\n"
},
{
"answer_id": 198382,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 0,
"selected": false,
"text": "<p>On topic but not quite an answer:</p>\n\n<p>Inserting and deleting is not an application that is applicable on arrays. It goes beyond \"Optimization\" and into bad programming.</p>\n\n<p>If this gets hidden in the bottom of a call structure and someone ends up calling it repeatedly, you could take a severe performance hit. In one case I changed an array insertion-sort to simply use a linked list and it changed runtime from 10+hours (locked the machine) to seconds/minutes).</p>\n\n<p>It was populating a listbox with ip addresses. As designed and tested on a class-c address space it worked fine, but we had requirements to work on a class-b address space without failing (Could take a while, but not hours). We were tasked with the minimum possible refactor to get it to not fail.</p>\n\n<p>Don't assume you know how your hack is going to be used.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
Which is faster? someCondition has the same probability of being true as it has of being false.
Insertion:
```
arrayList = Array("apple", "pear","grape")
if someCondition then
' insert "banana" element
end if
```
Deletion:
```
arrayList = Array("apple","banana","pear","grape")
if not someCondition then
' remove "banana" element
end if
```
It looks like it depends purely on the implementation of Insert and Remove. So which, in general, is faster? I'm leaning toward insertion because I've read that one can use CopyMemory to insert without looping. Is this the same for deletion? Does anyone have an example?
Edit:
This is VB6, not VB.NET.
For display reasons, I have to use insert rather than append.
|
For a delete, every item after the removed item must be shifted down.
For an Insert, space must be found for the new item. If there is empty space after the array that it can annex, then this takes no time, and the only time spend is more each item after the new item up, to make room in the middle.
If there is no available space locally, a whole new array must be allocated and every item copied.
So, when considering adding or deleting to the same array position, inserting could be as fast as deleting, but it maybe much longer. Inserting won't be faster.
|
198,141 |
<p>I have a postgres table. I need to delete some data from it. I was going to create a temporary table, copy the data in, recreate the indexes and the delete the rows I need. I can't delete data from the original table, because this original table is the source of data. In one case I need to get some results that depends on deleting X, in another case, I'll need to delete Y. So I need all the original data to always be around and available.</p>
<p>However it seems a bit silly to recreate the table and copy it again and recreate the indexes. Is there anyway in postgres to tell it "I want a complete separate copy of this table, including structure, data and indexes"?</p>
<p>Unfortunately PostgreSQL does not have a "CREATE TABLE .. LIKE X INCLUDING INDEXES'</p>
|
[
{
"answer_id": 198192,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Create a new table using a select to grab the data you want. Then swap the old table with the new one.</p>\n\n<pre><code>create table mynewone as select * from myoldone where ...\nmess (re-create) with indexes after the table swap.\n</code></pre>\n"
},
{
"answer_id": 198833,
"author": "WolfmanDragon",
"author_id": 13491,
"author_profile": "https://Stackoverflow.com/users/13491",
"pm_score": 6,
"selected": false,
"text": "<pre><code>[CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name\n [ (column_name [, ...] ) ]\n [ WITH ( storage_parameter [= value] [, ... ] ) | WITH OIDS | WITHOUT OIDS ]\n [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]\n [ TABLESPACE tablespace ]\n AS query][1] \n</code></pre>\n\n<p>Here is an <a href=\"http://developer.postgresql.org/pgdocs/postgres/sql-createtableas.html\" rel=\"noreferrer\">example</a></p>\n\n<pre><code>CREATE TABLE films_recent AS\n SELECT * FROM films WHERE date_prod >= '2002-01-01';\n</code></pre>\n\n<p>The other way to create a new table from the first is to use</p>\n\n<pre><code> CREATE TABLE films_recent (LIKE films INCLUDING INDEXES); \n\n INSERT INTO films_recent\n SELECT *\n FROM books\n WHERE date_prod >= '2002-01-01'; \n</code></pre>\n\n<p>Note that Postgresql has a <a href=\"http://people.planetpostgresql.org/dfetter/index.php?/archives/158-Postgres-Weekly-News-February-10-2008.html\" rel=\"noreferrer\">patch</a> out to fix tablespace issues if the second method is used</p>\n"
},
{
"answer_id": 198919,
"author": "Alan",
"author_id": 5878,
"author_profile": "https://Stackoverflow.com/users/5878",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I have a postgres table. I need to\n delete some data from it.</p>\n</blockquote>\n\n<p>I presume that ...</p>\n\n<pre><code>delete from yourtable\nwhere <condition(s)>\n</code></pre>\n\n<p>... won't work for some reason. (Care to share that reason?)</p>\n\n<blockquote>\n <p>I was going to create a temporary\n table, copy the data in, recreate the\n indexes and the delete the rows I\n need.</p>\n</blockquote>\n\n<p>Look into pg_dump and pg_restore. Using pg_dump with some clever options and perhaps editing the output before pg_restoring might do the trick.</p>\n\n<hr>\n\n<p>Since you are doing \"what if\"-type analysis on the data, I wonder if might you be better off using views. </p>\n\n<p>You could define a view for each scenario you want to test based on the negation of what you want to exclude. I.e., define a view based on what you want to INclude. E.g., if you want a \"window\" on the data where you \"deleted\" the rows where X=Y, then you would create a view as rows where (X != Y).</p>\n\n<p>Views are stored in the database (in the System Catalog) as their defining query. Every time you query the view the database server looks up the underlying query that defines it and executes that (ANDed with any other conditions you used). There are several benefits to this approach:</p>\n\n<ol>\n<li>You never duplicate any portion of your data.</li>\n<li>The indexes already in use for the base table (your original, \"real\" table) will be used (as seen fit by the query optimizer) when you query each view/scenario. There is no need to redefine or copy them.</li>\n<li>Since a view is a \"window\" (NOT a shapshot) on the \"real\" data in the base table, you can add/update/delete on your base table and simply re-query the view scenarios with no need to recreate anything as the data changes over time.</li>\n</ol>\n\n<p>There is a trade-off, of course. Since a view is a virtual table and not a \"real\" (base) table, you're actually executing a (perhaps complex) query every time you access it. This may slow things down a bit. But it may not. It depends on many issues (size and nature of the data, quality of the statistics in the System Catalog, speed of the hardware, usage load, and much more). You won't know until you try it. If (and only if) you actually find that the performance is unacceptably slow, then you might look at other options. (Materialized views, copies of tables, ... anything that trades space for time.)</p>\n"
},
{
"answer_id": 1079166,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>New PostgreSQL ( since 8.3 according to docs ) can use \"INCLUDING INDEXES\":</p>\n\n<pre><code># select version();\n version\n-------------------------------------------------------------------------------------------------\n PostgreSQL 8.3.7 on x86_64-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.4 (Ubuntu 4.2.4-1ubuntu3)\n(1 row)\n</code></pre>\n\n<p>As you can see I'm testing on 8.3.</p>\n\n<p>Now, let's create table:</p>\n\n<pre><code># create table x1 (id serial primary key, x text unique);\nNOTICE: CREATE TABLE will create implicit sequence \"x1_id_seq\" for serial column \"x1.id\"\nNOTICE: CREATE TABLE / PRIMARY KEY will create implicit index \"x1_pkey\" for table \"x1\"\nNOTICE: CREATE TABLE / UNIQUE will create implicit index \"x1_x_key\" for table \"x1\"\nCREATE TABLE\n</code></pre>\n\n<p>And see how it looks:</p>\n\n<pre><code># \\d x1\n Table \"public.x1\"\n Column | Type | Modifiers\n--------+---------+-------------------------------------------------\n id | integer | not null default nextval('x1_id_seq'::regclass)\n x | text |\nIndexes:\n \"x1_pkey\" PRIMARY KEY, btree (id)\n \"x1_x_key\" UNIQUE, btree (x)\n</code></pre>\n\n<p>Now we can copy the structure:</p>\n\n<pre><code># create table x2 ( like x1 INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES );\nNOTICE: CREATE TABLE / PRIMARY KEY will create implicit index \"x2_pkey\" for table \"x2\"\nNOTICE: CREATE TABLE / UNIQUE will create implicit index \"x2_x_key\" for table \"x2\"\nCREATE TABLE\n</code></pre>\n\n<p>And check the structure:</p>\n\n<pre><code># \\d x2\n Table \"public.x2\"\n Column | Type | Modifiers\n--------+---------+-------------------------------------------------\n id | integer | not null default nextval('x1_id_seq'::regclass)\n x | text |\nIndexes:\n \"x2_pkey\" PRIMARY KEY, btree (id)\n \"x2_x_key\" UNIQUE, btree (x)\n</code></pre>\n\n<p>If you are using PostgreSQL pre-8.3, you can simply use pg_dump with option \"-t\" to specify 1 table, change table name in dump, and load it again:</p>\n\n<pre><code>=> pg_dump -t x2 | sed 's/x2/x3/g' | psql\nSET\nSET\nSET\nSET\nSET\nSET\nSET\nSET\nCREATE TABLE\nALTER TABLE\nALTER TABLE\nALTER TABLE\n</code></pre>\n\n<p>And now the table is:</p>\n\n<pre><code># \\d x3\n Table \"public.x3\"\n Column | Type | Modifiers\n--------+---------+-------------------------------------------------\n id | integer | not null default nextval('x1_id_seq'::regclass)\n x | text |\nIndexes:\n \"x3_pkey\" PRIMARY KEY, btree (id)\n \"x3_x_key\" UNIQUE, btree (x)\n</code></pre>\n"
},
{
"answer_id": 56692379,
"author": "Ringtail",
"author_id": 5465064,
"author_profile": "https://Stackoverflow.com/users/5465064",
"pm_score": 2,
"selected": false,
"text": "<p>A simple way is include all:</p>\n\n<pre><code>CREATE TABLE new_table (LIKE original_table INCLUDING ALL);\n</code></pre>\n"
},
{
"answer_id": 59285499,
"author": "oshai",
"author_id": 411965,
"author_profile": "https://Stackoverflow.com/users/411965",
"pm_score": 4,
"selected": false,
"text": "<p>There are many answers on the web, one of them can be found <a href=\"https://www.technologyscout.net/2015/04/postgresql-copy-a-table-structure-and-data/\" rel=\"noreferrer\">here</a>.</p>\n\n<p>I ended up doing something like this:</p>\n\n<pre><code>create table NEW ( like ORIGINAL including all);\ninsert into NEW select * from ORIGINAL\n</code></pre>\n\n<p>This will copy the schema and the data including indexes, but not including triggers and constraints.\nNote that indexes are shared with original table so when adding new row to either table the counter will increment.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161922/"
] |
I have a postgres table. I need to delete some data from it. I was going to create a temporary table, copy the data in, recreate the indexes and the delete the rows I need. I can't delete data from the original table, because this original table is the source of data. In one case I need to get some results that depends on deleting X, in another case, I'll need to delete Y. So I need all the original data to always be around and available.
However it seems a bit silly to recreate the table and copy it again and recreate the indexes. Is there anyway in postgres to tell it "I want a complete separate copy of this table, including structure, data and indexes"?
Unfortunately PostgreSQL does not have a "CREATE TABLE .. LIKE X INCLUDING INDEXES'
|
New PostgreSQL ( since 8.3 according to docs ) can use "INCLUDING INDEXES":
```
# select version();
version
-------------------------------------------------------------------------------------------------
PostgreSQL 8.3.7 on x86_64-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.4 (Ubuntu 4.2.4-1ubuntu3)
(1 row)
```
As you can see I'm testing on 8.3.
Now, let's create table:
```
# create table x1 (id serial primary key, x text unique);
NOTICE: CREATE TABLE will create implicit sequence "x1_id_seq" for serial column "x1.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "x1_pkey" for table "x1"
NOTICE: CREATE TABLE / UNIQUE will create implicit index "x1_x_key" for table "x1"
CREATE TABLE
```
And see how it looks:
```
# \d x1
Table "public.x1"
Column | Type | Modifiers
--------+---------+-------------------------------------------------
id | integer | not null default nextval('x1_id_seq'::regclass)
x | text |
Indexes:
"x1_pkey" PRIMARY KEY, btree (id)
"x1_x_key" UNIQUE, btree (x)
```
Now we can copy the structure:
```
# create table x2 ( like x1 INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES );
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "x2_pkey" for table "x2"
NOTICE: CREATE TABLE / UNIQUE will create implicit index "x2_x_key" for table "x2"
CREATE TABLE
```
And check the structure:
```
# \d x2
Table "public.x2"
Column | Type | Modifiers
--------+---------+-------------------------------------------------
id | integer | not null default nextval('x1_id_seq'::regclass)
x | text |
Indexes:
"x2_pkey" PRIMARY KEY, btree (id)
"x2_x_key" UNIQUE, btree (x)
```
If you are using PostgreSQL pre-8.3, you can simply use pg\_dump with option "-t" to specify 1 table, change table name in dump, and load it again:
```
=> pg_dump -t x2 | sed 's/x2/x3/g' | psql
SET
SET
SET
SET
SET
SET
SET
SET
CREATE TABLE
ALTER TABLE
ALTER TABLE
ALTER TABLE
```
And now the table is:
```
# \d x3
Table "public.x3"
Column | Type | Modifiers
--------+---------+-------------------------------------------------
id | integer | not null default nextval('x1_id_seq'::regclass)
x | text |
Indexes:
"x3_pkey" PRIMARY KEY, btree (id)
"x3_x_key" UNIQUE, btree (x)
```
|
198,153 |
<pre><code><html>
<head>
<style type="text/css">
div {
border:1px solid #000;
min-width: 50%;
}
</style>
</head>
<body>
<div>This is some text. </div>
</body>
</html>
</code></pre>
<p>I believe the div should be 50 percent of the page, unless, for some reason, the text inside the div makes it larger. However, the border around the div stretches across the entire page width. This occurs in both IE and Firefox.</p>
<p>Suggestions?</p>
|
[
{
"answer_id": 198165,
"author": "Chris Serra",
"author_id": 13435,
"author_profile": "https://Stackoverflow.com/users/13435",
"pm_score": 4,
"selected": true,
"text": "<p>If you provide <code>absolute</code> positioning to the element, it will be <code>50%</code> in Firefox. However, IE doesn't like the <code>min-width</code> or <code>min-height</code> attributes, so you will have to define width as <code>50%</code> also for it to work in IE.</p>\n"
},
{
"answer_id": 198188,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<p>To add to what <a href=\"https://stackoverflow.com/questions/198153/why-does-the-css-min-width-attribute-not-force-a-div-to-have-the-specified-mini#198165\">Chris Serra said</a>, in IE < 7 (and in 7? I can't keep track these days, but definitely < 8), <code>width</code> behaves exactly like <code>min-width</code> is supposed to behave.</p>\n"
},
{
"answer_id": 198305,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 3,
"selected": false,
"text": "<p>Without <code>min-width</code>, your div will take whole page width, that is how <code>display:block</code> elements behave. Adding <code>min-width</code> cannot make it smaller.</p>\n\n<p>Changing <code>display</code> property to <code>absolute</code> or <code>float</code> property to <code>left</code> will make the element to shrink to fit contents. Then, <code>min-width</code> start to make sense.</p>\n"
},
{
"answer_id": 198947,
"author": "David Kolar",
"author_id": 3283,
"author_profile": "https://Stackoverflow.com/users/3283",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>I believe the div should be 50 percent of the page, unless, for some reason, the text inside the div makes it larger.</p>\n</blockquote>\n\n<p><code>min-width</code> does not set a minimum starting width from which your block will grow; rather it limits how far the block can shrink. </p>\n\n<p>In <code>min-width: 50%;</code>, the <code>50%</code> is in reference to the containing block. I've never used percentages with <code>min-width</code>, but I find it can be useful with other units. For example if I have a block (like a column of text) that I want to be full width, but I don't ever want it to go below a minimum width, I could use something like <code>{width: 100%; min-width: 250px;}</code>.</p>\n\n<p>Note the caveats on IE support mentioned by others.</p>\n"
},
{
"answer_id": 201878,
"author": "Traingamer",
"author_id": 27609,
"author_profile": "https://Stackoverflow.com/users/27609",
"pm_score": 2,
"selected": false,
"text": "<p>You are telling it that the minimum width is 50%. Since there is nothing else taking up the space, it will take all of it (except for margins).</p>\n\n<p>If you give it a max-width of say 75%, firefox should constrain it to that. IE6 will still ignore it. </p>\n\n<p>As David Kolar already said, many of us typically do not use percentages for min-width.</p>\n"
},
{
"answer_id": 273591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to try an IE specific style-sheet and include and expression like:</p>\n\n<pre><code>print(\"width:expression(document.body.clientWidth < 1024? \"50%\" : \"100%\");\");\n</code></pre>\n\n<p>This will change the width setting based on the width of the browser window at load time. I personally like to use px as the unit measurement, but you need to try it with your specific setup.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
```
<html>
<head>
<style type="text/css">
div {
border:1px solid #000;
min-width: 50%;
}
</style>
</head>
<body>
<div>This is some text. </div>
</body>
</html>
```
I believe the div should be 50 percent of the page, unless, for some reason, the text inside the div makes it larger. However, the border around the div stretches across the entire page width. This occurs in both IE and Firefox.
Suggestions?
|
If you provide `absolute` positioning to the element, it will be `50%` in Firefox. However, IE doesn't like the `min-width` or `min-height` attributes, so you will have to define width as `50%` also for it to work in IE.
|
198,157 |
<p>I'm trying to verify if a schema matches the objects I'm initializing.</p>
<p>Is there a way to get the TableName of a class other than simply reflecting the class name?</p>
<p>I am using some class with explicit TableNames</p>
<p>Edit: using Joe's solution I added the case where you don't specify the table name, it could probably use a constraint</p>
<pre><code>public string find_table_name(object obj)
{
object[] attribs = obj.GetType().GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);
if (attribs != null)
{
ActiveRecordAttribute attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
if (attrib.Table != null)
return attrib.Table;
return obj.GetType().Name;
}
return null;
}
</code></pre>
|
[
{
"answer_id": 198263,
"author": "user27529",
"author_id": 27529,
"author_profile": "https://Stackoverflow.com/users/27529",
"pm_score": 3,
"selected": true,
"text": "<p>If you have something like the following:</p>\n\n<pre><code>[ActiveRecord(Table = \"NewsMaster\")]\npublic class Article\n{\n [PrimaryKey(Generator = PrimaryKeyType.Identity)]\n public int NewsId { get; set; }\n\n [Property(Column = \"NewsHeadline\")]\n public string Headline { get; set; }\n\n [Property(Column = \"EffectiveStartDate\")]\n public DateTime StartDate { get; set; }\n\n [Property(Column = \"EffectiveEndDate\")]\n public DateTime EndDate { get; set; }\n\n [Property]\n public string NewsBlurb { get; set; }\n}\n</code></pre>\n\n<p>This will get you the table name:</p>\n\n<pre><code> [Test]\n public void Can_get_table_name()\n {\n var attribs = typeof(Article).GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);\n\n if (attribs != null)\n {\n var attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];\n Assert.AreEqual(\"NewsMaster\", attrib.Table);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 325635,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 2,
"selected": false,
"text": "<p>You could also use:</p>\n\n<pre><code>ActiveRecordModel.GetModel(typeof(Article)).ActiveRecordAtt.Table\n</code></pre>\n\n<p>see <a href=\"http://svn.castleproject.org:8080/svn/castle/trunk/ActiveRecord/Castle.ActiveRecord.Tests/PluralizationTestCase.cs\" rel=\"nofollow noreferrer\">this testcase</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253/"
] |
I'm trying to verify if a schema matches the objects I'm initializing.
Is there a way to get the TableName of a class other than simply reflecting the class name?
I am using some class with explicit TableNames
Edit: using Joe's solution I added the case where you don't specify the table name, it could probably use a constraint
```
public string find_table_name(object obj)
{
object[] attribs = obj.GetType().GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);
if (attribs != null)
{
ActiveRecordAttribute attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
if (attrib.Table != null)
return attrib.Table;
return obj.GetType().Name;
}
return null;
}
```
|
If you have something like the following:
```
[ActiveRecord(Table = "NewsMaster")]
public class Article
{
[PrimaryKey(Generator = PrimaryKeyType.Identity)]
public int NewsId { get; set; }
[Property(Column = "NewsHeadline")]
public string Headline { get; set; }
[Property(Column = "EffectiveStartDate")]
public DateTime StartDate { get; set; }
[Property(Column = "EffectiveEndDate")]
public DateTime EndDate { get; set; }
[Property]
public string NewsBlurb { get; set; }
}
```
This will get you the table name:
```
[Test]
public void Can_get_table_name()
{
var attribs = typeof(Article).GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);
if (attribs != null)
{
var attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
Assert.AreEqual("NewsMaster", attrib.Table);
}
}
```
|
198,174 |
<p>I have found jQuery to be a great tool to simplify my MVC Views.</p>
<p>For example, instead of including complicated logic to add alternating styles to my tables I just do this...</p>
<pre><code>$(document).ready(function() {
$("table.details tr:odd").addClass("detailsAlternatingRow");
$("table.details tr:even").addClass("detailsRow");
});
</code></pre>
<p>Do you know of any other good uses of jQuery to slim down the logic in my MVC View?</p>
|
[
{
"answer_id": 198186,
"author": "roundcrisis",
"author_id": 162325,
"author_profile": "https://Stackoverflow.com/users/162325",
"pm_score": 2,
"selected": false,
"text": "<p>Implementing an observer <a href=\"http://google-ajax-examples.googlecode.com/svn/trunk/customevents/jquery.html\" rel=\"nofollow noreferrer\">http://google-ajax-examples.googlecode.com/svn/trunk/customevents/jquery.html</a> proved a really good practise.\nReally nice for code maintenance.</p>\n"
},
{
"answer_id": 198226,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "<p>Note if you use PHP on the server you can use <a href=\"http://code.google.com/p/phpquery/\" rel=\"nofollow noreferrer\">phpQuery</a> (and I'm sure there are similar server-side jQuery ports for other languages) to do stuff like that without expecting the user to have Javascript enabled.</p>\n"
},
{
"answer_id": 198563,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 3,
"selected": true,
"text": "<p>MVC Framework has a JsonResult that can be very nice to eliminate server round trips and might be able to get rid of some of the logic in your view page. I wrote a tutorial on this available at : </p>\n\n<p><a href=\"http://www.dev102.com/2008/08/19/jquery-and-the-aspnet-mvc-framework/\" rel=\"nofollow noreferrer\">http://www.dev102.com/2008/08/19/jquery-and-the-aspnet-mvc-framework/</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4481/"
] |
I have found jQuery to be a great tool to simplify my MVC Views.
For example, instead of including complicated logic to add alternating styles to my tables I just do this...
```
$(document).ready(function() {
$("table.details tr:odd").addClass("detailsAlternatingRow");
$("table.details tr:even").addClass("detailsRow");
});
```
Do you know of any other good uses of jQuery to slim down the logic in my MVC View?
|
MVC Framework has a JsonResult that can be very nice to eliminate server round trips and might be able to get rid of some of the logic in your view page. I wrote a tutorial on this available at :
<http://www.dev102.com/2008/08/19/jquery-and-the-aspnet-mvc-framework/>
|
198,196 |
<p>I'm curious to know how people are using table aliases. The other developers where I work always use table aliases, and always use the alias of a, b, c, etc.</p>
<p>Here's an example:</p>
<pre><code>SELECT a.TripNum, b.SegmentNum, b.StopNum, b.ArrivalTime
FROM Trip a, Segment b
WHERE a.TripNum = b.TripNum
</code></pre>
<p>I disagree with them, and think table aliases should be use more sparingly. </p>
<p>I think they should be used when including the same table twice in a query, or when the table name is very long and using a shorter name in the query will make the query easier to read. </p>
<p>I also think the alias should be a descriptive name rather than just a letter. In the above example, if I felt I needed to use 1 letter table alias I would use t for the Trip table and s for the segment table.</p>
|
[
{
"answer_id": 198207,
"author": "Adam Caviness",
"author_id": 9130,
"author_profile": "https://Stackoverflow.com/users/9130",
"pm_score": 0,
"selected": false,
"text": "<p>I feel that you should use them as often as possible but I do agree that t & s represent the entities better than a & b.</p>\n\n<p>This boils down to, like everything else, preferences. I like that you can depend on your stored procedures following the same conventions when each developer uses the alias in the same manner.</p>\n\n<p>Go convince your coworkers to get on the same page as you or this is all worthless. The alternative is you could have a table Zebra as first table and alias it as a. That would just be cute.</p>\n"
},
{
"answer_id": 198214,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 4,
"selected": false,
"text": "<p>I use them to save typing. However, I always use letters similar to the function. So, in your example, I would type:</p>\n\n<pre><code>SELECT t.TripNum, s.SegmentNum, s.StopNum, s.ArrivalTime \nFROM Trip t, Segment s \nWHERE t.TripNum = s.TripNum\n</code></pre>\n\n<p>That just makes it easier to read, for me.</p>\n"
},
{
"answer_id": 198216,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": -1,
"selected": false,
"text": "<p>Always. Make it a habit.</p>\n"
},
{
"answer_id": 198228,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>i only use them when they are necessary to distinguish which table a field is coming from</p>\n\n<pre><code>select PartNumber, I.InventoryTypeId, InventoryTypeDescription\nfrom dbo.Inventory I\n inner join dbo.InventoryType IT on IT.InventoryTypeId = I.InventoryTypeId\n</code></pre>\n\n<p>In the example above both tables have an InventoryTypeId field, but the other field names are unique.</p>\n\n<p>Always use an abbreviation for the table as the name so that the code makes more sense - ask your other developers if they name their local variables A, B, C, etc!</p>\n\n<p>The only exception is in the rare cases where the SQL syntax requires a table alias but it isn't referenced, e.g.</p>\n\n<pre><code>select *\nfrom (\n select field1, field2, sum(field3) as total\n from someothertable\n) X\n</code></pre>\n\n<p>In the above, SQL syntax requires the table alias for the subselect, but it isn't referenced anywhere so I get lazy and use X or something like that.</p>\n"
},
{
"answer_id": 198246,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 3,
"selected": false,
"text": "<p>As a general rule <strong>I always use them</strong>, as there are usually multiple joins going on in my stored procedures. It also makes it easier when using code generation tools like CodeSmith to have it generate the alias name automatically for you. </p>\n\n<p>I try to stay away from single letters like a & b, as I may have multiple tables that start with the letter a or b. I go with a longer approach, the concatenation of the referenced foreign key with the alias table, for example CustomerContact ... this would be the alias for the Customer table when joining to a Contact table.</p>\n\n<p>The other reason I don't mind <strong>longer</strong> name, is due to most of my stored procedures are being generated via code CodeSmith. I don't mind hand typing the <strong>few</strong> that I may have to build myself.</p>\n\n<p>Using the current example, I would do something like:</p>\n\n<pre><code>SELECT TripNum, TripSegment.SegmentNum, TripSegment.StopNum, TripSegment.ArrivalTime \nFROM Trip, Segment TripSegment \nWHERE TripNum = TripSegment.TripNum\n</code></pre>\n"
},
{
"answer_id": 198249,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 5,
"selected": false,
"text": "<p>There are two reasons for using table aliases.</p>\n\n<p>The first is cosmetic. The statements are easier to write, and perhaps also easier to read when table aliases are used. </p>\n\n<p>The second is more substantive. If a table appears more than once in the FROM clause, you need table aliases in order to keep them distinct. Self joins are common in cases where a table contains a foreign key that references the primary key of the same table.</p>\n\n<p>Two examples: an employees table that contains a supervisorID column that references the employeeID of the supervisor.</p>\n\n<p>The second is a parts explosion. Often, this is implemented in a separate table with three columns: ComponentPartID, AssemblyPartID, and Quantity. In this case, there won't be any self joins, but there will often be a three way join between this table and two different references to the table of Parts.</p>\n\n<p>It's a good habit to get into. </p>\n"
},
{
"answer_id": 198269,
"author": "Jeff Schumacher",
"author_id": 27498,
"author_profile": "https://Stackoverflow.com/users/27498",
"pm_score": 0,
"selected": false,
"text": "<p>I find it nothing more than a preference. As mentioned above, aliases save typing, especially with long table/view names.</p>\n"
},
{
"answer_id": 198277,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Using the full name makes it harder to read, especially for larger queries or the Order/Product/OrderProduct scenari0</p>\n\n<p>I'd use t and s. Or o/p/op</p>\n\n<p>If you use SCHEMABINDING then columns must be qualified anyway</p>\n\n<p>If you add a column to a base table, then the qualification reduces the chance of a duplicate in the query (for example a \"Comment\" column)</p>\n\n<p>Because of this qualification, it makes sense to always use aliases.</p>\n\n<p>Using a and b is blind obedience to a bizarre standard.</p>\n"
},
{
"answer_id": 198298,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 2,
"selected": false,
"text": "<p>I use it always, reasons:</p>\n\n<ul>\n<li>leaving full tables names in statements makes them hard to read, plus you cannot have a same table twice</li>\n<li>not using anything is a very bad idea, because later you could add some field to one of the tables that is already present in some other table</li>\n</ul>\n\n<p>Consider this example:</p>\n\n<pre><code>select col1, col2\nfrom tab1\njoin tab2 on tab1.col3 = tab2.col3\n</code></pre>\n\n<p>Now, imagine a few months later, you decide to add column named 'col1' to tab2. Database will silently allow you to do that, but applications would break when executing the above query because of ambiguity between tab1.col1 and tab2.col1. </p>\n\n<p>But, I agree with you on the naming: a, b, c is fine, but <strong>t</strong> and <strong>s</strong> would be much better in your example. And when I have the same table more than once, I would use t1, t2, ... or s1, s2, s3... </p>\n"
},
{
"answer_id": 199091,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 0,
"selected": false,
"text": "<p>One thing I've learned is that especially with complex queries; it is far simpler to troubleshoot six months later if you use the alias as a qualifier for every field reference. Then you aren't trying to remember which table that field came from.</p>\n\n<p>We tend to have some ridiculously long table names, so I find it easier to read if the tables are aliased. And of course you must do it if you are using a derived table or a self join, so being in the habit is a good idea. I find most of our developers end up using the same alias for each table in all their sps,so most of the time anyone reading it will immediately know what pug is the alias for or mmh.</p>\n"
},
{
"answer_id": 200353,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 0,
"selected": false,
"text": "<p>I always use them. I formerly only used them in queries involving just one table but then I realized a) queries involving just one table are rare, and b) queries involving just one table rarely stay that way for long. So I always put them in from the start so that I (or someone else) won't have to retro fit them later. Oh and BTW: I call them \"correlation names\", as per the SQL-92 Standard :)</p>\n"
},
{
"answer_id": 223342,
"author": "Noah Yetter",
"author_id": 30080,
"author_profile": "https://Stackoverflow.com/users/30080",
"pm_score": 0,
"selected": false,
"text": "<p>Tables aliases should be four things:</p>\n\n<ol>\n<li>Short</li>\n<li>Meaningful</li>\n<li>Always used</li>\n<li>Used consistently</li>\n</ol>\n\n<p>For example if you had tables named service_request, service_provider, user, and affiliate (among many others) a good practice would be to alias those tables as \"sr\", \"sp\", \"u\", and \"a\", and do so in every query possible. This is especially convenient if, as is often the case, these aliases coincide with acronyms used by your organization. So if \"SR\" and \"SP\" are the accepted terms for Service Request and Service Provider respectively, the aliases above carry a double payload of intuitively standing in for both the table and the business object it represents.</p>\n\n<p>The obvious flaws with this system are first that it can be awkward for table names with lots of \"words\" e.g. a_long_multi_word_table_name which would alias to almwtn or something, and that it's likely you'll end up with tables named such that they abbreviate the same. The first flaw can be dealt with however you like, such as by taking the last 3 or 4 letters, or whichever subset you feel is most representative, most unique, or easiest to type. The second I've found in practice isn't as troublesome as it might seem, perhaps just by luck. You can also do things like take the second letter of a \"word\" in the table as well, such as aliasing account_transaction to \"atr\" instead of \"at\" to avoid conflicting with account_type.</p>\n\n<p>Of course whether you use the above approach or not, aliases should be short because you'll be typing them very very frequently, and they should always be used because once you've written a query against a single table and omitted the alias, it's inevitable that you'll later need to edit in a second table with duplicate column names.</p>\n"
},
{
"answer_id": 1229380,
"author": "Erv",
"author_id": 149519,
"author_profile": "https://Stackoverflow.com/users/149519",
"pm_score": 1,
"selected": false,
"text": "<p>In simple queries I do not use aliases. In queries whit multiple tables I always use them because:</p>\n\n<ul>\n<li>they make queries more readable (my\naliases are 2 or more capital letters that is a shortcut for the table name and if possible\na relationship to other\ntables) </li>\n<li>they allow faster developing and\nrewriting (my table names are long and have prefixes depending on role they pose)</li>\n</ul>\n\n<p>so instead of for example:</p>\n\n<pre><code>SELECT SUM(a.VALUE) \n FROM Domesticvalues a, Foreignvalues b \n WHERE a.Value>b.Value\n AND a.Something ...\n</code></pre>\n\n<p>I write:</p>\n\n<pre><code>select SUM(DVAL.Value) \n from DomesticValues DVAL, ForeignValues FVAL \n where DVAL.Value > FVAL.Value\n and DVAL.Something ...\n</code></pre>\n"
},
{
"answer_id": 3062808,
"author": "MJB",
"author_id": 223858,
"author_profile": "https://Stackoverflow.com/users/223858",
"pm_score": 2,
"selected": false,
"text": "<p>Can I add to a debate that is already several years old?</p>\n\n<p>There is another reason that no one has mentioned. The SQL parser in certain databases works better with an alias. I cannot recall if Oracle changed this in later versions, but when it came to an alias, it looked up the columns in the database and remembered them. When it came to a table name, even if it was already encountered in the statement, it re-checked the database for the columns. So using an alias allowed for faster parsing, especially of long SQL statements. I am sure someone knows if this is still the case, if other databases do this at parse time, and if it changed, <strong><em>when</em></strong> it changed.</p>\n"
},
{
"answer_id": 48309677,
"author": "Benjamin Ford",
"author_id": 9231749,
"author_profile": "https://Stackoverflow.com/users/9231749",
"pm_score": 1,
"selected": false,
"text": "<p>There are many good ideas in the posts above about when and why to alias table names. What no one else has mentioned is that it is also beneficial in helping a maintainer understand the scope of tables. At our company we are not allowed to create views. (Thank the DBA.) So, some of our queries become large, even exceeding the 50,000 character limit of a SQL command in Crystal Reports. When a query aliases its tables as a, b, c, and a subquery of that does the same, and multiple subqueries in that one each use the same aliases, it is easy for one to mistake what level of the query is being read. This can even confuse the original developer when enough time has passed. Using unique aliases within each level of a query makes it easier to read because the scope remains clear.</p>\n"
},
{
"answer_id": 55837172,
"author": "AdamQuark",
"author_id": 4754934,
"author_profile": "https://Stackoverflow.com/users/4754934",
"pm_score": 0,
"selected": false,
"text": "<p>Because I always fully qualify my tables, I use aliases to provide a shorter name for the fields being SELECTed when JOINed tables are involved. I think it makes my code easier to follow.</p>\n\n<p>If the query deals with only one source - no JOINs - then I don't use an alias.</p>\n\n<p>Just a matter of personal preference.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28281/"
] |
I'm curious to know how people are using table aliases. The other developers where I work always use table aliases, and always use the alias of a, b, c, etc.
Here's an example:
```
SELECT a.TripNum, b.SegmentNum, b.StopNum, b.ArrivalTime
FROM Trip a, Segment b
WHERE a.TripNum = b.TripNum
```
I disagree with them, and think table aliases should be use more sparingly.
I think they should be used when including the same table twice in a query, or when the table name is very long and using a shorter name in the query will make the query easier to read.
I also think the alias should be a descriptive name rather than just a letter. In the above example, if I felt I needed to use 1 letter table alias I would use t for the Trip table and s for the segment table.
|
There are two reasons for using table aliases.
The first is cosmetic. The statements are easier to write, and perhaps also easier to read when table aliases are used.
The second is more substantive. If a table appears more than once in the FROM clause, you need table aliases in order to keep them distinct. Self joins are common in cases where a table contains a foreign key that references the primary key of the same table.
Two examples: an employees table that contains a supervisorID column that references the employeeID of the supervisor.
The second is a parts explosion. Often, this is implemented in a separate table with three columns: ComponentPartID, AssemblyPartID, and Quantity. In this case, there won't be any self joins, but there will often be a three way join between this table and two different references to the table of Parts.
It's a good habit to get into.
|
198,199 |
<p>How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?</p>
|
[
{
"answer_id": 198200,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>#include <cstdio>\n#include <cstdlib>\n#include <string>\n\nvoid strrev(char *str)\n{\n if( str == NULL )\n return;\n\n char *end_ptr = &str[strlen(str) - 1];\n char temp;\n while( end_ptr > str )\n {\n temp = *str;\n *str++ = *end_ptr;\n *end_ptr-- = temp;\n }\n}\n\nint main(int argc, char *argv[])\n{\n char buffer[32];\n\n strcpy(buffer, \"testing\");\n strrev(buffer);\n printf(\"%s\\n\", buffer);\n\n strcpy(buffer, \"a\");\n strrev(buffer);\n printf(\"%s\\n\", buffer);\n\n strcpy(buffer, \"abc\");\n strrev(buffer);\n printf(\"%s\\n\", buffer);\n\n strcpy(buffer, \"\");\n strrev(buffer);\n printf(\"%s\\n\", buffer);\n\n strrev(NULL);\n\n return 0;\n}\n</code></pre>\n\n<p>This code produces this output:</p>\n\n<pre><code>gnitset\na\ncba\n</code></pre>\n"
},
{
"answer_id": 198210,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 9,
"selected": false,
"text": "<pre><code>#include <algorithm>\nstd::reverse(str.begin(), str.end());\n</code></pre>\n\n<p>This is the simplest way in C++.</p>\n"
},
{
"answer_id": 198264,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 8,
"selected": true,
"text": "<p>The standard algorithm is to use pointers to the start / end, and walk them inward until they meet or cross in the middle. Swap as you go.</p>\n\n<hr>\n\n<p>Reverse ASCII string, i.e. a 0-terminated array where every character fits in 1 <code>char</code>. (Or other non-multibyte character sets).</p>\n\n<pre><code>void strrev(char *head)\n{\n if (!head) return;\n char *tail = head;\n while(*tail) ++tail; // find the 0 terminator, like head+strlen\n --tail; // tail points to the last real char\n // head still points to the first\n for( ; head < tail; ++head, --tail) {\n // walk pointers inwards until they meet or cross in the middle\n char h = *head, t = *tail;\n *head = t; // swapping as we go\n *tail = h;\n }\n}\n</code></pre>\n\n<p></p>\n\n<pre><code>// test program that reverses its args\n#include <stdio.h>\n\nint main(int argc, char **argv)\n{\n do {\n printf(\"%s \", argv[argc-1]);\n strrev(argv[argc-1]);\n printf(\"%s\\n\", argv[argc-1]);\n } while(--argc);\n\n return 0;\n}\n</code></pre>\n\n<p>The same algorithm works for integer arrays with known length, just use <code>tail = start + length - 1</code> instead of the end-finding loop.</p>\n\n<p>(Editor's note: this answer originally used XOR-swap for this simple version, too. Fixed for the benefit of future readers of this popular question. <a href=\"https://stackoverflow.com/questions/10549155/why-swap-dont-use-xor-operation-in-c\">XOR-swap is <em>highly</em> not recommended</a>; hard to read and making your code compile less efficiently. You can see <a href=\"https://godbolt.org/z/pPNxJq\" rel=\"noreferrer\">on the Godbolt compiler explorer</a> how much more complicated the asm loop body is when xor-swap is compiled for x86-64 with gcc -O3.)</p>\n\n<hr>\n\n<h2>Ok, fine, let's fix the UTF-8 chars...</h2>\n\n<p>(This is XOR-swap thing. Take care to note that you <em>must avoid</em> swapping with self, because if <code>*p</code> and <code>*q</code> are the same location you'll zero it with a^a==0. XOR-swap depends on having two distinct locations, using them each as temporary storage.)</p>\n\n<p>Editor's note: you can replace SWP with a safe inline function using a tmp variable.</p>\n\n<pre><code>#include <bits/types.h>\n#include <stdio.h>\n\n#define SWP(x,y) (x^=y, y^=x, x^=y)\n\nvoid strrev(char *p)\n{\n char *q = p;\n while(q && *q) ++q; /* find eos */\n for(--q; p < q; ++p, --q) SWP(*p, *q);\n}\n\nvoid strrev_utf8(char *p)\n{\n char *q = p;\n strrev(p); /* call base case */\n\n /* Ok, now fix bass-ackwards UTF chars. */\n while(q && *q) ++q; /* find eos */\n while(p < --q)\n switch( (*q & 0xF0) >> 4 ) {\n case 0xF: /* U+010000-U+10FFFF: four bytes. */\n SWP(*(q-0), *(q-3));\n SWP(*(q-1), *(q-2));\n q -= 3;\n break;\n case 0xE: /* U+000800-U+00FFFF: three bytes. */\n SWP(*(q-0), *(q-2));\n q -= 2;\n break;\n case 0xC: /* fall-through */\n case 0xD: /* U+000080-U+0007FF: two bytes. */\n SWP(*(q-0), *(q-1));\n q--;\n break;\n }\n}\n\nint main(int argc, char **argv)\n{\n do {\n printf(\"%s \", argv[argc-1]);\n strrev_utf8(argv[argc-1]);\n printf(\"%s\\n\", argv[argc-1]);\n } while(--argc);\n\n return 0;\n}\n</code></pre>\n\n<ul>\n<li>Why, yes, if the input is borked, this will cheerfully swap outside the place.</li>\n<li>Useful link when vandalising in the UNICODE: <a href=\"http://www.macchiato.com/unicode/chart/\" rel=\"noreferrer\">http://www.macchiato.com/unicode/chart/</a></li>\n<li>Also, UTF-8 over 0x10000 is untested (as I don't seem to have any font for it, nor the patience to use a hexeditor)</li>\n</ul>\n\n<p>Examples:</p>\n\n<pre><code>$ ./strrev Räksmörgås ░▒▓○◔◑◕●\n\n░▒▓○◔◑◕● ●◕◑◔○▓▒░\n\nRäksmörgås sågrömskäR\n\n./strrev verrts/.\n</code></pre>\n"
},
{
"answer_id": 198275,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": false,
"text": "<p>Non-evil C, assuming the common case where the string is a null-terminated <code>char</code> array:</p>\n\n<pre><code>#include <stddef.h>\n#include <string.h>\n\n/* PRE: str must be either NULL or a pointer to a \n * (possibly empty) null-terminated string. */\nvoid strrev(char *str) {\n char temp, *end_ptr;\n\n /* If str is NULL or empty, do nothing */\n if( str == NULL || !(*str) )\n return;\n\n end_ptr = str + strlen(str) - 1;\n\n /* Swap the chars */\n while( end_ptr > str ) {\n temp = *str;\n *str = *end_ptr;\n *end_ptr = temp;\n str++;\n end_ptr--;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 198458,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 4,
"selected": false,
"text": "<p>In the interest of completeness, it should be pointed out that there are representations of strings on various platforms in which the number of bytes per character <strong><em>varies</em></strong> depending on the character. Old-school programmers would refer to this as <a href=\"http://en.wikipedia.org/wiki/DBCS\" rel=\"nofollow noreferrer\">DBCS (Double Byte Character Set)</a>. Modern programmers more commonly encounter this in <a href=\"http://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow noreferrer\">UTF-8</a> (as well as <a href=\"http://en.wikipedia.org/wiki/UTF-16\" rel=\"nofollow noreferrer\">UTF-16</a> and others). There are other such encodings as well.</p>\n\n<p>In any of these variable-width encoding schemes, the simple algorithms posted here (<a href=\"https://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c#198264\">evil</a>, <a href=\"https://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c#198275\">non-evil</a> or <a href=\"https://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c#198200\">otherwise</a>) would not work correctly at all! In fact, they could even cause the string to become illegible or even an illegal string in that encoding scheme. See <a href=\"https://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c#198637\">Juan Pablo Califano's answer</a> for some good examples.</p>\n\n<p>std::reverse() potentially would still work in this case, as long as your platform's implementation of the Standard C++ Library (in particular, string iterators) properly took this into account.</p>\n"
},
{
"answer_id": 198527,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 5,
"selected": false,
"text": "<p>Note that the beauty of std::reverse is that it works with <code>char *</code> strings and <code>std::wstring</code>s just as well as <code>std::string</code>s</p>\n\n<pre><code>void strrev(char *str)\n{\n if (str == NULL)\n return;\n std::reverse(str, str + strlen(str));\n}\n</code></pre>\n"
},
{
"answer_id": 198637,
"author": "Juan Pablo Califano",
"author_id": 24170,
"author_profile": "https://Stackoverflow.com/users/24170",
"pm_score": 4,
"selected": false,
"text": "<p>If you're looking for reversing NULL terminated buffers, most solutions posted here are OK. But, as Tim Farley already pointed out, these algorithms will work only if it's valid to assume that a string is semantically an array of bytes (i.e. single-byte strings), which is a wrong assumption, I think. </p>\n\n<p>Take for example, the string \"año\" (year in Spanish).</p>\n\n<p>The Unicode code points are 0x61, 0xf1, 0x6f.</p>\n\n<p>Consider some of the most used encodings:</p>\n\n<p><strong>Latin1 / iso-8859-1</strong> (single byte encoding, 1 character is 1 byte and vice versa):</p>\n\n<blockquote>\n <p>Original:</p>\n \n <p>0x61, 0xf1, 0x6f, 0x00</p>\n \n <p>Reverse:</p>\n \n <p>0x6f, 0xf1, 0x61, 0x00</p>\n \n <p><strong>The result is OK</strong></p>\n</blockquote>\n\n<p><strong>UTF-8:</strong></p>\n\n<blockquote>\n <p>Original:</p>\n \n <p>0x61, 0xc3, 0xb1, 0x6f, 0x00</p>\n \n <p>Reverse:</p>\n \n <p>0x6f, 0xb1, 0xc3, 0x61, 0x00</p>\n \n <p><strong>The result is gibberish and an illegal UTF-8 sequence</strong></p>\n</blockquote>\n\n<p><strong>UTF-16 Big Endian:</strong></p>\n\n<blockquote>\n <p>Original:</p>\n \n <p>0x00, 0x61, 0x00, 0xf1, 0x00, 0x6f, 0x00, 0x00</p>\n \n <p><strong>The first byte will be treated as a NUL-terminator. No reversing will take place.</strong></p>\n</blockquote>\n\n<p><strong>UTF-16 Little Endian:</strong></p>\n\n<blockquote>\n <p>Original:</p>\n \n <p>0x61, 0x00, 0xf1, 0x00, 0x6f, 0x00, 0x00, 0x00</p>\n \n <p><strong>The second byte will be treated as a NUL-terminator. The result will be 0x61, 0x00, a string containing the 'a' character.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 199891,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>Read Kernighan and Ritchie</p>\n\n<pre><code>#include <string.h>\n\nvoid reverse(char s[])\n{\n int length = strlen(s) ;\n int c, i, j;\n\n for (i = 0, j = length - 1; i < j; i++, j--)\n {\n c = s[i];\n s[i] = s[j];\n s[j] = c;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 200081,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 2,
"selected": false,
"text": "<p>In case you are using GLib, it has two functions for that, <a href=\"http://library.gnome.org/devel/glib/stable/glib-String-Utility-Functions.html#g-strreverse\" rel=\"nofollow noreferrer\">g_strreverse()</a> and <a href=\"http://library.gnome.org/devel/glib/stable/glib-Unicode-Manipulation.html#g-utf8-strreverse\" rel=\"nofollow noreferrer\">g_utf8_strreverse()</a></p>\n"
},
{
"answer_id": 5315651,
"author": "Rob",
"author_id": 386102,
"author_profile": "https://Stackoverflow.com/users/386102",
"pm_score": 2,
"selected": false,
"text": "<p>I like Evgeny's K&R answer. However, it is nice to see a version using pointers. Otherwise, it's essentially the same:</p>\n\n<pre><code>#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nchar *reverse(char *str) {\n if( str == NULL || !(*str) ) return NULL;\n int i, j = strlen(str)-1;\n char *sallocd;\n sallocd = malloc(sizeof(char) * (j+1));\n for(i=0; j>=0; i++, j--) {\n *(sallocd+i) = *(str+j);\n }\n return sallocd;\n}\n\nint main(void) {\n char *s = \"a man a plan a canal panama\";\n char *sret = reverse(s);\n printf(\"%s\\n\", reverse(sret));\n free(sret);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 6560310,
"author": "karlphillip",
"author_id": 176769,
"author_profile": "https://Stackoverflow.com/users/176769",
"pm_score": 5,
"selected": false,
"text": "<p>It's been a while and I don't remember which book taught me this algorithm, but I thought it was quite ingenious and simple to understand:</p>\n<pre><code>char input[] = "moc.wolfrevokcats";\n\nint length = strlen(input);\nint last_pos = length-1;\nfor(int i = 0; i < length/2; i++)\n{\n char tmp = input[i];\n input[i] = input[last_pos - i];\n input[last_pos - i] = tmp;\n}\n\nprintf("%s\\n", input);\n</code></pre>\n<p>A visualization of this algorithm, courtesy of <a href=\"https://stackoverflow.com/users/901444/slashdottir\">slashdottir</a>:</p>\n<p><img src=\"https://i.stack.imgur.com/LLSbH.gif\" alt=\"Visualization of the algorithm to reverse a string in place\" /></p>\n"
},
{
"answer_id": 9393226,
"author": "Simon Peverett",
"author_id": 6063,
"author_profile": "https://Stackoverflow.com/users/6063",
"pm_score": 2,
"selected": false,
"text": "<p>Recursive function to reverse a string in place (no extra buffer, malloc).</p>\n\n<p>Short, sexy code. Bad, bad stack usage. </p>\n\n<pre><code>#include <stdio.h>\n\n/* Store the each value and move to next char going down\n * the stack. Assign value to start ptr and increment \n * when coming back up the stack (return).\n * Neat code, horrible stack usage.\n *\n * val - value of current pointer.\n * s - start pointer\n * n - next char pointer in string.\n */\nchar *reverse_r(char val, char *s, char *n)\n{\n if (*n)\n s = reverse_r(*n, s, n+1);\n *s = val;\n return s+1;\n}\n\n/*\n * expect the string to be passed as argv[1]\n */\nint main(int argc, char *argv[])\n{\n char *aString;\n\n if (argc < 2)\n {\n printf(\"Usage: RSIP <string>\\n\");\n return 0;\n }\n\n aString = argv[1];\n printf(\"String to reverse: %s\\n\", aString );\n\n reverse_r(*aString, aString, aString+1); \n printf(\"Reversed String: %s\\n\", aString );\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 10955108,
"author": "Mike Marrotte",
"author_id": 1445312,
"author_profile": "https://Stackoverflow.com/users/1445312",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another:</p>\n\n<pre><code>#include <stdio.h>\n#include <strings.h>\n\nint main(int argc, char **argv) {\n\n char *reverse = argv[argc-1];\n char *left = reverse;\n int length = strlen(reverse);\n char *right = reverse+length-1;\n char temp;\n\n while(right-left>=1){\n\n temp=*left;\n *left=*right;\n *right=temp;\n ++left;\n --right;\n\n }\n\n printf(\"%s\\n\", reverse);\n\n}\n</code></pre>\n"
},
{
"answer_id": 12640695,
"author": "pprzemek",
"author_id": 212149,
"author_profile": "https://Stackoverflow.com/users/212149",
"pm_score": 3,
"selected": false,
"text": "<p>Another C++ way (though I would probably use std::reverse() myself :) as being more expressive and faster)</p>\n\n<pre><code>str = std::string(str.rbegin(), str.rend());\n</code></pre>\n\n<p>The C way (more or less :) )\nand please, be careful about XOR trick for swapping, \ncompilers sometimes cannot optimize that.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice\" rel=\"nofollow noreferrer\">In such case it is usually much slower.</a></p>\n\n<pre><code>char* reverse(char* s)\n{\n char* beg = s, *end = s, tmp;\n while (*end) end++;\n while (end-- > beg)\n { \n tmp = *beg; \n *beg++ = *end; \n *end = tmp;\n }\n return s;\n} // fixed: check history for details, as those are interesting ones\n</code></pre>\n"
},
{
"answer_id": 19674312,
"author": "masakielastic",
"author_id": 531320,
"author_profile": "https://Stackoverflow.com/users/531320",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n\nunsigned char * utf8_reverse(const unsigned char *, int);\nvoid assert_true(bool);\n\nint main(void)\n{\n unsigned char str[] = \"mañana mañana\";\n unsigned char *ret = utf8_reverse(str, strlen((const char *) str) + 1);\n\n printf(\"%s\\n\", ret);\n assert_true(0 == strncmp((const char *) ret, \"anãnam anañam\", strlen(\"anãnam anañam\") + 1));\n\n free(ret);\n\n return EXIT_SUCCESS;\n}\n\nunsigned char * utf8_reverse(const unsigned char *str, int size)\n{\n unsigned char *ret = calloc(size, sizeof(unsigned char*));\n int ret_size = 0;\n int pos = size - 2;\n int char_size = 0;\n\n if (str == NULL) {\n fprintf(stderr, \"failed to allocate memory.\\n\");\n exit(EXIT_FAILURE);\n }\n\n while (pos > -1) {\n\n if (str[pos] < 0x80) {\n char_size = 1;\n } else if (pos > 0 && str[pos - 1] > 0xC1 && str[pos - 1] < 0xE0) {\n char_size = 2;\n } else if (pos > 1 && str[pos - 2] > 0xDF && str[pos - 2] < 0xF0) {\n char_size = 3;\n } else if (pos > 2 && str[pos - 3] > 0xEF && str[pos - 3] < 0xF5) {\n char_size = 4;\n } else {\n char_size = 1;\n }\n\n pos -= char_size;\n memcpy(ret + ret_size, str + pos + 1, char_size);\n ret_size += char_size;\n } \n\n ret[ret_size] = '\\0';\n\n return ret;\n}\n\nvoid assert_true(bool boolean)\n{\n puts(boolean == true ? \"true\" : \"false\");\n}\n</code></pre>\n"
},
{
"answer_id": 19717084,
"author": "Michael Haephrati",
"author_id": 1592639,
"author_profile": "https://Stackoverflow.com/users/1592639",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using ATL/MFC <code>CString</code>, simply call <code>CString::MakeReverse()</code>.</p>\n"
},
{
"answer_id": 23706832,
"author": "Stephen J",
"author_id": 1028958,
"author_profile": "https://Stackoverflow.com/users/1028958",
"pm_score": -1,
"selected": false,
"text": "<p>If you don't need to store it, you can reduce the time spent like this:</p>\n\n<pre><code>void showReverse(char s[], int length)\n{\n printf(\"Reversed String without storing is \");\n //could use another variable to test for length, keeping length whole.\n //assumes contiguous memory\n for (; length > 0; length--)\n {\n printf(\"%c\", *(s+ length-1) );\n }\n printf(\"\\n\");\n}\n</code></pre>\n"
},
{
"answer_id": 65927657,
"author": "Cameron Lowell Palmer",
"author_id": 410867,
"author_profile": "https://Stackoverflow.com/users/410867",
"pm_score": 0,
"selected": false,
"text": "<h2>C++ multi-byte UTF-8 reverser</h2>\n<p>My thought is that you can never just swap ends, you must always move from beginning-to-end, move through the string and look for "how many bytes will this character require?" I attach the character starting at the original end position, and remove the character from the front of the string.</p>\n<pre><code>void StringReverser(std::string *original)\n{\n int eos = original->length() - 1;\n while (eos > 0) {\n char c = (*original)[0];\n int characterBytes;\n switch( (c & 0xF0) >> 4 ) {\n case 0xC:\n case 0xD: /* U+000080-U+0007FF: two bytes. */\n characterBytes = 2;\n break;\n case 0xE: /* U+000800-U+00FFFF: three bytes. */\n characterBytes = 3;\n break;\n case 0xF: /* U+010000-U+10FFFF: four bytes. */\n characterBytes = 4;\n break;\n default:\n characterBytes = 1;\n break;\n }\n\n for (int i = 0; i < characterBytes; i++) {\n original->insert(eos+i, 1, (*original)[i]);\n }\n original->erase(0, characterBytes);\n eos -= characterBytes;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 66070496,
"author": "RobinSingh",
"author_id": 866614,
"author_profile": "https://Stackoverflow.com/users/866614",
"pm_score": 0,
"selected": false,
"text": "<pre><code>void reverseString(vector<char>& s) {\n int l = s.size();\n char ch ;\n int i = 0 ;\n int j = l-1;\n while(i < j){\n s[i] = s[i]^s[j];\n s[j] = s[i]^s[j];\n s[i] = s[i]^s[j];\n i++;\n j--;\n }\n for(char c : s)\n cout <<c ;\n cout<< endl;\n}\n</code></pre>\n"
},
{
"answer_id": 69962399,
"author": "Kateridzhe",
"author_id": 14200717,
"author_profile": "https://Stackoverflow.com/users/14200717",
"pm_score": -1,
"selected": false,
"text": "<p>In C++ the reverse can be done in a function:</p>\n<pre><code>#include <algorithm>\n#include <string>\n\nvoid backwards(vector<string> &inputs_ref) {\n for (auto i = inputs_ref.begin(); i != inputs_ref.end(); ++i) {\n reverse(i->begin(), i->end());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73584850,
"author": "Driver",
"author_id": 19091624,
"author_profile": "https://Stackoverflow.com/users/19091624",
"pm_score": 0,
"selected": false,
"text": "<p>input string, return string, No other library required</p>\n<pre><code>std::string reverse_string(std::string &str)\n{ \n const char*buf = str.c_str();\n char *start = const_cast<char*>(buf);\n char *end = start + strlen(buf) - 1;\n char t;\n\n while(start < end)\n {\n t = *start;\n *start = *end;\n *end = t;\n start ++;\n end --;\n }\n str = buf;\n return str;\n}\n</code></pre>\n<pre><code>std::string md1 = "abcdefghijklmnopqrstuvwxyz0123456789";\nstd::cout << reverse_string(md1) << std::endl;\n\n//9876543210zyxwvutsrqponmlkjihgfedcba\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?
|
The standard algorithm is to use pointers to the start / end, and walk them inward until they meet or cross in the middle. Swap as you go.
---
Reverse ASCII string, i.e. a 0-terminated array where every character fits in 1 `char`. (Or other non-multibyte character sets).
```
void strrev(char *head)
{
if (!head) return;
char *tail = head;
while(*tail) ++tail; // find the 0 terminator, like head+strlen
--tail; // tail points to the last real char
// head still points to the first
for( ; head < tail; ++head, --tail) {
// walk pointers inwards until they meet or cross in the middle
char h = *head, t = *tail;
*head = t; // swapping as we go
*tail = h;
}
}
```
```
// test program that reverses its args
#include <stdio.h>
int main(int argc, char **argv)
{
do {
printf("%s ", argv[argc-1]);
strrev(argv[argc-1]);
printf("%s\n", argv[argc-1]);
} while(--argc);
return 0;
}
```
The same algorithm works for integer arrays with known length, just use `tail = start + length - 1` instead of the end-finding loop.
(Editor's note: this answer originally used XOR-swap for this simple version, too. Fixed for the benefit of future readers of this popular question. [XOR-swap is *highly* not recommended](https://stackoverflow.com/questions/10549155/why-swap-dont-use-xor-operation-in-c); hard to read and making your code compile less efficiently. You can see [on the Godbolt compiler explorer](https://godbolt.org/z/pPNxJq) how much more complicated the asm loop body is when xor-swap is compiled for x86-64 with gcc -O3.)
---
Ok, fine, let's fix the UTF-8 chars...
--------------------------------------
(This is XOR-swap thing. Take care to note that you *must avoid* swapping with self, because if `*p` and `*q` are the same location you'll zero it with a^a==0. XOR-swap depends on having two distinct locations, using them each as temporary storage.)
Editor's note: you can replace SWP with a safe inline function using a tmp variable.
```
#include <bits/types.h>
#include <stdio.h>
#define SWP(x,y) (x^=y, y^=x, x^=y)
void strrev(char *p)
{
char *q = p;
while(q && *q) ++q; /* find eos */
for(--q; p < q; ++p, --q) SWP(*p, *q);
}
void strrev_utf8(char *p)
{
char *q = p;
strrev(p); /* call base case */
/* Ok, now fix bass-ackwards UTF chars. */
while(q && *q) ++q; /* find eos */
while(p < --q)
switch( (*q & 0xF0) >> 4 ) {
case 0xF: /* U+010000-U+10FFFF: four bytes. */
SWP(*(q-0), *(q-3));
SWP(*(q-1), *(q-2));
q -= 3;
break;
case 0xE: /* U+000800-U+00FFFF: three bytes. */
SWP(*(q-0), *(q-2));
q -= 2;
break;
case 0xC: /* fall-through */
case 0xD: /* U+000080-U+0007FF: two bytes. */
SWP(*(q-0), *(q-1));
q--;
break;
}
}
int main(int argc, char **argv)
{
do {
printf("%s ", argv[argc-1]);
strrev_utf8(argv[argc-1]);
printf("%s\n", argv[argc-1]);
} while(--argc);
return 0;
}
```
* Why, yes, if the input is borked, this will cheerfully swap outside the place.
* Useful link when vandalising in the UNICODE: <http://www.macchiato.com/unicode/chart/>
* Also, UTF-8 over 0x10000 is untested (as I don't seem to have any font for it, nor the patience to use a hexeditor)
Examples:
```
$ ./strrev Räksmörgås ░▒▓○◔◑◕●
░▒▓○◔◑◕● ●◕◑◔○▓▒░
Räksmörgås sågrömskäR
./strrev verrts/.
```
|
198,215 |
<pre><code>int main()
{
HandPhone A,B;
A>>B;//overloading operator>> to simulate sending sms to another handphone(object)
return 0;
}
</code></pre>
<p>How should I declare the istream operator to simulate sending sms to another handphone(object)?</p>
|
[
{
"answer_id": 198227,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.cplusplus.com/reference/iostream/istream/\" rel=\"nofollow noreferrer\">std::istream</a> is a class, not an operator. The << and >> operators can be defined for any two types:</p>\n\n<pre><code>class A;\nclass B;\n\nA operator << (A& a, const B& b) // a << b; sends b to a.\n{\n a.sendMessage(b);\n return a;\n}\n</code></pre>\n"
},
{
"answer_id": 198539,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": false,
"text": "<p>This is how to define the >> operator:</p>\n\n<pre><code>void operator >> (HandPhone& a, HandPhone& b)\n{\n // Add code here.\n}\n</code></pre>\n\n<p>I have set the return type to void as I am not sure chaining would make sense.</p>\n\n<p>But it is considered bad design (in the C++ world) to overload operators to do random tasks as it makes the code hard to read. The streaming operators >> and << have a very well defined meaning but sending a message does not look that much like streaming that I would would want to to use the operator this way. I would expect that unmarshalling the object at the destination end of the stream would produce an object very similar to what was placed in at the source end.</p>\n\n<p>It is a lot easier to do something like this.</p>\n\n<pre><code>B.sendMessageTo(A,Message(\"PLOP\"));\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
int main()
{
HandPhone A,B;
A>>B;//overloading operator>> to simulate sending sms to another handphone(object)
return 0;
}
```
How should I declare the istream operator to simulate sending sms to another handphone(object)?
|
This is how to define the >> operator:
```
void operator >> (HandPhone& a, HandPhone& b)
{
// Add code here.
}
```
I have set the return type to void as I am not sure chaining would make sense.
But it is considered bad design (in the C++ world) to overload operators to do random tasks as it makes the code hard to read. The streaming operators >> and << have a very well defined meaning but sending a message does not look that much like streaming that I would would want to to use the operator this way. I would expect that unmarshalling the object at the destination end of the stream would produce an object very similar to what was placed in at the source end.
It is a lot easier to do something like this.
```
B.sendMessageTo(A,Message("PLOP"));
```
|
198,233 |
<p>How can I make my window not have a title bar but appear in the task bar with some descriptive text?
If you set the Form's .Text property then .net gives it a title bar, which I don't want.</p>
<pre><code> this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = true;
this.Text = "My title for task bar";
</code></pre>
<p>I've found a partial solution, to override CreateParams: </p>
<pre><code> protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams cp = base.CreateParams;
cp.Style &= ~0x00C00000; // WS_CAPTION
return cp;
}
}
</code></pre>
<p>However this causes my window to be resized as if they have a title bar, ie it's taller than it should be. Is there any good solution to this?</p>
|
[
{
"answer_id": 198287,
"author": "amcoder",
"author_id": 26898,
"author_profile": "https://Stackoverflow.com/users/26898",
"pm_score": 2,
"selected": false,
"text": "<p>Just set the border style to None.</p>\n\n<pre><code>this.FormBorderStyle = FormBorderStyle.None;\n</code></pre>\n"
},
{
"answer_id": 198290,
"author": "Jon Schneider",
"author_id": 12484,
"author_profile": "https://Stackoverflow.com/users/12484",
"pm_score": 4,
"selected": true,
"text": "<p>One approach to look into might be to set the <code>FormBorderStyle</code> property of your <code>Form</code> to <code>None</code> (instead of <code>FixedDialog</code>). </p>\n\n<p>The drawback to this approach is that you lose the borders of your window as well as the Titlebar. A result of this is that you lose the form repositioning/resizing logic that you normally get \"for free\" with Windows Forms; you would need to deal with this by implementing your own form move/resize logic in the form's MouseDown and MouseMove event handlers.</p>\n\n<p>I would also be interested to hear about better solutions.</p>\n"
},
{
"answer_id": 198328,
"author": "BlackWasp",
"author_id": 21862,
"author_profile": "https://Stackoverflow.com/users/21862",
"pm_score": 2,
"selected": false,
"text": "<p>Once you have removed the borders with the FormBorderStyle, as mentioned already, you can make it draggable fairly easily. I describe this at <a href=\"http://www.blackwasp.co.uk/DraggableBorderless.aspx\" rel=\"nofollow noreferrer\">http://www.blackwasp.co.uk/DraggableBorderless.aspx</a>.</p>\n"
},
{
"answer_id": 3162167,
"author": "LorenzCK",
"author_id": 3118,
"author_profile": "https://Stackoverflow.com/users/3118",
"pm_score": 3,
"selected": false,
"text": "<p>In my case I have a Form with <code>FormBorderStyle = FormBorderStyle.SizableToolWindow</code> and the following <code>CreateParams</code> override did the trick (i.e. I now have a form without caption and without additional margin for the title, but it keeps the title in the task bar):</p>\n\n<pre><code>protected override System.Windows.Forms.CreateParams CreateParams\n{\n get\n {\n var parms = base.CreateParams;\n parms.Style &= ~0x00C00000; // remove WS_CAPTION\n parms.Style |= 0x00040000; // include WS_SIZEBOX\n return parms;\n }\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8479/"
] |
How can I make my window not have a title bar but appear in the task bar with some descriptive text?
If you set the Form's .Text property then .net gives it a title bar, which I don't want.
```
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = true;
this.Text = "My title for task bar";
```
I've found a partial solution, to override CreateParams:
```
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams cp = base.CreateParams;
cp.Style &= ~0x00C00000; // WS_CAPTION
return cp;
}
}
```
However this causes my window to be resized as if they have a title bar, ie it's taller than it should be. Is there any good solution to this?
|
One approach to look into might be to set the `FormBorderStyle` property of your `Form` to `None` (instead of `FixedDialog`).
The drawback to this approach is that you lose the borders of your window as well as the Titlebar. A result of this is that you lose the form repositioning/resizing logic that you normally get "for free" with Windows Forms; you would need to deal with this by implementing your own form move/resize logic in the form's MouseDown and MouseMove event handlers.
I would also be interested to hear about better solutions.
|
198,240 |
<p>I'm looking to use Java to parse an ongoing stream of event drive XML generated by a remote device. Here's a simplified sample of two events:</p>
<pre><code><?xml version="1.0"?>
<Event> DeviceEventMsg
<Param1>SomeParmValue</Param1>
</Event>
<?xml version="1.0"?>
<Event> DeviceEventMsg
<Param1>SomeParmValue</Param1>
</Event>
</code></pre>
<p>It seems like SAX is more suited to this than DOM because it is an ongoing stream, though I'm not as familiar with Sax. Don't yell at me for the structure of the XML - I know it already and can't change it. </p>
<p>And yes the device DOES send the xml directive before every event. My first problem is that the second xml processing instruction is croaking the SAX parser. </p>
<p>Can anyone suggest a way to get around that?</p>
<hr>
<p>The code I'm using so far which is croaking on the second xml processing instruction is:</p>
<pre><code>public class TestMe extends HandlerBase {
public void startDocument () throws SAXException
{
System.out.println("got startDocument");
}
public void endDocument () throws SAXException
{
System.out.println("got endDocument");
}
public void startElement (String name, AttributeList attrs) throws SAXException
{
System.out.println("got startElement");
}
public void endElement (String name) throws SAXException
{
System.out.println("got endElement");
}
public void characters (char buf [], int offset, int len) throws SAXException
{
System.out.println("found characters");
}
public void processingInstruction (String target, String data) throws SAXException
{
System.out.println("got processingInstruction");
}
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
// using a file as test input for now
saxParser.parse( new File("devmodule.xml"), new TestMe() );
} catch (Throwable err) {
err.printStackTrace ();
}
}
}
</code></pre>
|
[
{
"answer_id": 198304,
"author": "eishay",
"author_id": 16201,
"author_profile": "https://Stackoverflow.com/users/16201",
"pm_score": 1,
"selected": false,
"text": "<p>Try to use <a href=\"http://en.wikipedia.org/wiki/StAX\" rel=\"nofollow noreferrer\">StAX</a> instead of SAX. StAX allows much more flexibility and it is a better solution for streaming XML. There are few implementations of StAX, I am very happy with the <a href=\"http://stax.codehaus.org/Download\" rel=\"nofollow noreferrer\">codehaus</a> one, but there is also one from <a href=\"https://sjsxp.dev.java.net/\" rel=\"nofollow noreferrer\">Sun</a>.\nIt might solve you're problems. </p>\n"
},
{
"answer_id": 199102,
"author": "simon",
"author_id": 6040,
"author_profile": "https://Stackoverflow.com/users/6040",
"pm_score": 0,
"selected": false,
"text": "<p>If you print out the name for the start and end element System.out.println() you will get something like this:</p>\n\n<blockquote>\n <p>got startDocument got startElement\n Event found characters found\n characters got startElement Param1\n found characters got endElement Param1\n found characters got endElement Event\n org.xml.sax.SAXParseException: The\n processing instruction target matching\n \"[xX][mM][lL]\" is not allowed. ...</p>\n</blockquote>\n\n<p>So I think the second </p>\n\n<blockquote>\n <p><code><?xml version=\"1.0\"?></code></p>\n</blockquote>\n\n<p>without getting an endDocument is causing a parser problem.</p>\n"
},
{
"answer_id": 199143,
"author": "simon",
"author_id": 6040,
"author_profile": "https://Stackoverflow.com/users/6040",
"pm_score": 0,
"selected": false,
"text": "<p>If you add this:</p>\n\n<pre><code>catch(SAXException SaxErr){\n System.out.println(\"ignore this error\");\n }\n</code></pre>\n\n<p>before the other catch you will catch this particular error. you would then have to reopen the device or for the static file case you may have to keep track of were you are in the file.</p>\n\n<p>Or at the end Event event, close the device/File and then reopen it for the next event.</p>\n"
},
{
"answer_id": 199193,
"author": "razlebe",
"author_id": 27615,
"author_profile": "https://Stackoverflow.com/users/27615",
"pm_score": 0,
"selected": false,
"text": "<p>RE: Simon's suggestion of catching the SAXException to determine when you've come to the end of one XML document and reached the start of another, I think this would be a problematic approach. If another error occurred(for whatever reason), you wouldn't be able to tell whether the exception had been thrown due to erroneous XML or because you'd reached the end of a document. </p>\n\n<p>The problem is that the parser is for processing an XML document; not a stream of several XML documents. I would suggest writing some code to manually parse the incoming data stream, breaking it into individual streams containing a single XML document; and then pass these streams to the XML parser in serial (so guaranteeing the order of your events). </p>\n"
},
{
"answer_id": 583134,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 1,
"selected": false,
"text": "<p>One more suggestion, specifically regarding multiple xml declarations. Yes, this is ILLEGAL xml, so proper parsers will barf on it using default modes.\nBut some parsers have alternate \"multi-document\" modes. For example, Woodstox has this, so you can check out:</p>\n\n<p><a href=\"http://www.cowtowncoder.com/blog/archives/2008/04/entry_66.html\" rel=\"nofollow noreferrer\">http://www.cowtowncoder.com/blog/archives/2008/04/entry_66.html</a></p>\n\n<p>Basically, you have to tell parser (via input factory) that input is in form of \"multiple xml documents\" (ParsingMode.PARSING_MODE_DOCUMENTS).</p>\n\n<p>If so, it will accept multiple xml declarations, each one indicating start of a new document.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27524/"
] |
I'm looking to use Java to parse an ongoing stream of event drive XML generated by a remote device. Here's a simplified sample of two events:
```
<?xml version="1.0"?>
<Event> DeviceEventMsg
<Param1>SomeParmValue</Param1>
</Event>
<?xml version="1.0"?>
<Event> DeviceEventMsg
<Param1>SomeParmValue</Param1>
</Event>
```
It seems like SAX is more suited to this than DOM because it is an ongoing stream, though I'm not as familiar with Sax. Don't yell at me for the structure of the XML - I know it already and can't change it.
And yes the device DOES send the xml directive before every event. My first problem is that the second xml processing instruction is croaking the SAX parser.
Can anyone suggest a way to get around that?
---
The code I'm using so far which is croaking on the second xml processing instruction is:
```
public class TestMe extends HandlerBase {
public void startDocument () throws SAXException
{
System.out.println("got startDocument");
}
public void endDocument () throws SAXException
{
System.out.println("got endDocument");
}
public void startElement (String name, AttributeList attrs) throws SAXException
{
System.out.println("got startElement");
}
public void endElement (String name) throws SAXException
{
System.out.println("got endElement");
}
public void characters (char buf [], int offset, int len) throws SAXException
{
System.out.println("found characters");
}
public void processingInstruction (String target, String data) throws SAXException
{
System.out.println("got processingInstruction");
}
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
// using a file as test input for now
saxParser.parse( new File("devmodule.xml"), new TestMe() );
} catch (Throwable err) {
err.printStackTrace ();
}
}
}
```
|
Try to use [StAX](http://en.wikipedia.org/wiki/StAX) instead of SAX. StAX allows much more flexibility and it is a better solution for streaming XML. There are few implementations of StAX, I am very happy with the [codehaus](http://stax.codehaus.org/Download) one, but there is also one from [Sun](https://sjsxp.dev.java.net/).
It might solve you're problems.
|
198,244 |
<p>I have a checkstyle suppression filter setup (e.g. ignore magic numbers in unit test code).</p>
<p>The suppression xml file resides in the same folder as the checkstyle xml file. However, where this file actually is varies:
on my windows dev box it is in d:\dev\shared\checkstyle\config
on the Linux CI server it will be in /root/repo/shared/checkstyle/config
on another developers box it could be anywhere (they check out their svn repo to).</p>
<p>The only "consistent" thing is that the suppression file is always in the same folder as the checkstyle xml file.
I cannot work out how to ensure that this file is always consistently picked up. Also I don't know why checkstyle does not support embedded suppression within the checkstyle xml file.</p>
<p>any help?</p>
|
[
{
"answer_id": 199291,
"author": "Greg Mattes",
"author_id": 13940,
"author_profile": "https://Stackoverflow.com/users/13940",
"pm_score": 5,
"selected": true,
"text": "<p>I had this same problem with the Checkstyle suppression configuration when I was going back and forth between Linux and Windows. Here's how I solved it in my Ant-based build system:</p>\n\n<p>Basically, I inject the proper, platform-specific directory value into the main Checkstyle configuration file by configuring a Checkstyle properties file with an Ant build script.</p>\n\n<p>My main Checkstyle configuration file has a <code>SuppressionFilter</code> module declaration as shown below. The value of the <code>checkstyle-suppressions-file</code> property comes from a Checkstyle properties file:</p>\n\n<pre><code><module name=\"SuppressionFilter\">\n <property name=\"file\" value=\"${checkstyle-suppressions-file}\"/>\n</module>\n</code></pre>\n\n<p>The Checkstyle properties file is not static, it is generated by an Ant build script from a properties file template called <code>template-checkstyle.properties</code>. Here's what the template looks like for the suppressions file property:</p>\n\n<pre><code>checkstyle-suppressions-file=@SCM_DIR@/checkstyle_suppressions.xml\n</code></pre>\n\n<p>My Ant build script copies this file to a file named <code>checkstyle.properties</code>. The copy has the special token replaced with the proper value of the directory in which the suppressions file is found:</p>\n\n<pre><code><copy file=\"${scm.dir}/template-checkstyle.properties\" tofile=\"${scm.dir}/checkstyle.properties\">\n <filterset>\n <filter token=\"SCM_DIR\" value=\"${scm.dir.unix}\"/>\n </filterset>\n</copy>\n</code></pre>\n\n<p>Now, where does the value of <code>scm.dir.unix</code> come from? Well, it's <em>derived</em> from a property of my build, read on. You'll need to specify such a value with the directory values that you mentioned.</p>\n\n<p>Note that there is one slightly non-obvious issue concerning the way in which you specify this directory. I say that the <code>scm.dir.unix</code> value is derived from a build property because I observed that the main Checkstyle configuration file cannot contain backslashes, i.e. Windows path separator characters, in the value of the <code>file</code> property of the <code>SuppressionFilter</code> module. For example, specifying something like <code>C:\\foo\\bar\\baz</code> leads to a Checkstyle error message saying that <code>C:foobarbaz</code> cannot be found. I work around this by \"converting\" the <code>scm.dir</code> directory build property to a \"unix\" format with Ant's <code>pathconvert</code> task:</p>\n\n<pre><code><pathconvert targetos=\"unix\" property=\"scm.dir.unix\">\n <path location=\"${scm.dir}\"/>\n</pathconvert>\n</code></pre>\n\n<p>Then I call the <code>checkstyle</code> Ant task like this:</p>\n\n<pre><code><checkstyle config=\"${scm.dir}/checkstyle_checks.xml\"\n properties=\"${scm.dir}/checkstyle.properties\">\n <!-- details elided -->\n</checkstyle>\n</code></pre>\n\n<p>The call to the <code>checkstyle</code> task injects the key/value pairs contained in the <code>checkstyle.properties</code> file into the main Checkstyle configuration.</p>\n\n<p>If you like, you can see the full scripts <a href=\"http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/scm/\" rel=\"noreferrer\">here</a></p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 945071,
"author": "gibbss",
"author_id": 116621,
"author_profile": "https://Stackoverflow.com/users/116621",
"pm_score": 2,
"selected": false,
"text": "<p>I get the absolute path to the directory where <code>build.xml</code> resides using the <code>ant.file</code> variable and the name of the project:</p>\n\n<pre><code><project name=\"common\" ... >\n <dirname property=\"thisdir\" file=\"${ant.file.common}\"/>\n</code></pre>\n\n<p>Then I can concatenate an absolute path to my checkstyle config files:</p>\n\n<pre><code>checkstyle.suppressions.file=${thisdir}/qclib/checkstyle-suppressions.xml\n</code></pre>\n\n<p>Since the <code>thisdir</code> variable comes from ant, it does not seem to need path separator conversion.</p>\n"
},
{
"answer_id": 8020122,
"author": "Jörg",
"author_id": 745640,
"author_profile": "https://Stackoverflow.com/users/745640",
"pm_score": 2,
"selected": false,
"text": "<p>If you are working with eclipse and you have the suppression file in the same directory as the external checkstyle config, you can set up a suppression filter like this:</p>\n\n<pre><code><module name=\"SuppressionFilter\">\n <property name=\"file\" value=\"${config_dir}/my_suppressions.xml\"/>\n</module>\n</code></pre>\n\n<p>You also must define the ${config_dir} property in the checkstyle configuration:</p>\n\n<p>Eclipse Preferences -> \"Checkstyle\" -> Choose your cs config -> \"Properties ..\" -> \"Additional Properties ..\"</p>\n\n<p>Define a property for the checkstyle config dir:</p>\n\n<pre><code>config_dir ---> ${config_loc}\n</code></pre>\n"
},
{
"answer_id": 15010596,
"author": "Robert Hutto",
"author_id": 2096840,
"author_profile": "https://Stackoverflow.com/users/2096840",
"pm_score": 3,
"selected": false,
"text": "<p>In eclipse I put the following which did not require me to add any additional properties:</p>\n\n<pre><code><module name=\"SuppressionFilter\">\n <property name=\"file\" value=\"${samedir}/suppressions.xml\"/>\n</module>\n</code></pre>\n"
},
{
"answer_id": 15226808,
"author": "Sebastian vom Meer",
"author_id": 579849,
"author_profile": "https://Stackoverflow.com/users/579849",
"pm_score": 1,
"selected": false,
"text": "<p>I think Robert's answer can be extended to an easy solution for <strong>ant and Eclipse</strong>:</p>\n\n<p>Include the suppression file inside your config XML like this:</p>\n\n<pre><code><module name=\"SuppressionFilter\">\n <property name=\"file\" value=\"${samedir}/suppressions.xml\"/>\n</module>\n</code></pre>\n\n<p>Now, Eclipse is satisfied and finds the file.</p>\n\n<p>To get ant to work update your target to something like this:</p>\n\n<pre><code><checkstyle config=\"${checkstyle.config}/checkstyle-checks.xml\">\n <!-- ... -->\n <property key=\"samedir\" value=\"${checkstyle.config}\"/>\n</checkstyle>\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 51795099,
"author": "Jérémie DERUETTE",
"author_id": 8029150,
"author_profile": "https://Stackoverflow.com/users/8029150",
"pm_score": 0,
"selected": false,
"text": "<p>Since CheckStyle 4.26.0 you can use predefined constants in your config files.</p>\n\n<p>(<a href=\"https://github.com/jshiell/checkstyle-idea/issues/217\" rel=\"nofollow noreferrer\">https://github.com/jshiell/checkstyle-idea/issues/217</a>) : </p>\n\n<blockquote>\n <ul>\n <li>${basedir} & ${project_loc} - gets mapped to the current project directory</li>\n <li>${workspace_loc} - gets mapped to the current Eclipse workspace directory</li>\n <li>${config_loc} & ${samedir} - get mapped to the directory the configuration file lies in</li>\n </ul>\n</blockquote>\n\n<p>If you want to share the config with maven you will need to \"alias\" the \"eclipse constants\" in your POM configuration (in the reporting section) using the \"propertyExpansion\" configuration element : </p>\n\n<pre><code><plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-checkstyle-plugin</artifactId>\n <version>3.0.0</version>\n <configuration>\n <configLocation>${project.basedir}/quality/checkstyle/dap_checkstyle_checks.xml</configLocation>\n <propertyExpansion>basedir=${project.basedir}</propertyExpansion>\n </configuration>\n <reportSets>\n <reportSet>\n <reports>\n <report>checkstyle</report>\n </reports>\n </reportSet>\n </reportSets>\n</plugin>\n</code></pre>\n\n<p>The \"propertyExpansion\" is inspired from : <a href=\"https://github.com/checkstyle/checkstyle/blob/master/pom.xml#L582\" rel=\"nofollow noreferrer\">https://github.com/checkstyle/checkstyle/blob/master/pom.xml#L582</a>.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27522/"
] |
I have a checkstyle suppression filter setup (e.g. ignore magic numbers in unit test code).
The suppression xml file resides in the same folder as the checkstyle xml file. However, where this file actually is varies:
on my windows dev box it is in d:\dev\shared\checkstyle\config
on the Linux CI server it will be in /root/repo/shared/checkstyle/config
on another developers box it could be anywhere (they check out their svn repo to).
The only "consistent" thing is that the suppression file is always in the same folder as the checkstyle xml file.
I cannot work out how to ensure that this file is always consistently picked up. Also I don't know why checkstyle does not support embedded suppression within the checkstyle xml file.
any help?
|
I had this same problem with the Checkstyle suppression configuration when I was going back and forth between Linux and Windows. Here's how I solved it in my Ant-based build system:
Basically, I inject the proper, platform-specific directory value into the main Checkstyle configuration file by configuring a Checkstyle properties file with an Ant build script.
My main Checkstyle configuration file has a `SuppressionFilter` module declaration as shown below. The value of the `checkstyle-suppressions-file` property comes from a Checkstyle properties file:
```
<module name="SuppressionFilter">
<property name="file" value="${checkstyle-suppressions-file}"/>
</module>
```
The Checkstyle properties file is not static, it is generated by an Ant build script from a properties file template called `template-checkstyle.properties`. Here's what the template looks like for the suppressions file property:
```
checkstyle-suppressions-file=@SCM_DIR@/checkstyle_suppressions.xml
```
My Ant build script copies this file to a file named `checkstyle.properties`. The copy has the special token replaced with the proper value of the directory in which the suppressions file is found:
```
<copy file="${scm.dir}/template-checkstyle.properties" tofile="${scm.dir}/checkstyle.properties">
<filterset>
<filter token="SCM_DIR" value="${scm.dir.unix}"/>
</filterset>
</copy>
```
Now, where does the value of `scm.dir.unix` come from? Well, it's *derived* from a property of my build, read on. You'll need to specify such a value with the directory values that you mentioned.
Note that there is one slightly non-obvious issue concerning the way in which you specify this directory. I say that the `scm.dir.unix` value is derived from a build property because I observed that the main Checkstyle configuration file cannot contain backslashes, i.e. Windows path separator characters, in the value of the `file` property of the `SuppressionFilter` module. For example, specifying something like `C:\foo\bar\baz` leads to a Checkstyle error message saying that `C:foobarbaz` cannot be found. I work around this by "converting" the `scm.dir` directory build property to a "unix" format with Ant's `pathconvert` task:
```
<pathconvert targetos="unix" property="scm.dir.unix">
<path location="${scm.dir}"/>
</pathconvert>
```
Then I call the `checkstyle` Ant task like this:
```
<checkstyle config="${scm.dir}/checkstyle_checks.xml"
properties="${scm.dir}/checkstyle.properties">
<!-- details elided -->
</checkstyle>
```
The call to the `checkstyle` task injects the key/value pairs contained in the `checkstyle.properties` file into the main Checkstyle configuration.
If you like, you can see the full scripts [here](http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/scm/)
Hope this helps
|
198,266 |
<p>Can anyone provide and example of downloading a PDF file using Watin? I tried the SaveAsDialogHandler but I couldn't figure it out. Perhaps a MemoryStream could be used?</p>
<p>Thanks,</p>
<p>--jb</p>
|
[
{
"answer_id": 201464,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This code will do the trick. The UsedialogOnce class can be found in the WatiN.UnitTests code and will be part of the WatiN 1.3 release (which will probably be released tonigh 14 october).</p>\n\n<p>FileDownloadHandler fileDownloadHandler = new FileDownloadHandler(file.FullName);\nusing (new UseDialogOnce(ie.DialogWatcher, fileDownloadHandler))\n{\n ie.Button(\"exportPdfButtonId\").ClickNoWait();</p>\n\n<pre><code>fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(30);\nfileDownloadHandler.WaitUntilDownloadCompleted(200);\n</code></pre>\n\n<p>}</p>\n\n<p>HTH,\nJeroen van Menen\nLead developer WatiN</p>\n"
},
{
"answer_id": 201470,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>FileDownloadHandler fileDownloadHandler = new FileDownloadHandler(file.FullName);\nusing (new UseDialogOnce(ie.DialogWatcher, fileDownloadHandler))\n{\n ie.Button(\"exportPdfButtonId\").ClickNoWait();\n\n fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(30);\n fileDownloadHandler.WaitUntilDownloadCompleted(200);\n}\n</code></pre>\n"
},
{
"answer_id": 291671,
"author": "Matt Honeycutt",
"author_id": 32353,
"author_profile": "https://Stackoverflow.com/users/32353",
"pm_score": 1,
"selected": false,
"text": "<p>I just ran into this same issue, except I use Foxit instead of Acrobat. I told Foxit not to run in the browser, then this code started working just fine. Here's a complete unit test that should do the trick:</p>\n\n<pre><code> string file = Path.Combine(Directory.GetCurrentDirectory(), \"test.pdf\");\n\n using (IE ie = new IE())\n {\n FileDownloadHandler handler = new FileDownloadHandler(file);\n\n using (new UseDialogOnce(ie.DialogWatcher, handler))\n {\n try\n {\n ie.GoToNoWait(\"http://www.tug.org/texshowcase/cheat.pdf\");\n\n //WatiN seems to hang when IE loads a PDF, so let it timeout...\n ie.WaitForComplete(5);\n }\n catch (Exception)\n {\n //Ok.\n }\n\n handler.WaitUntilFileDownloadDialogIsHandled(30);\n handler.WaitUntilDownloadCompleted(30);\n }\n\n }\n\n Assert.That(File.Exists(file));\n</code></pre>\n"
},
{
"answer_id": 1466955,
"author": "MoMo",
"author_id": 176728,
"author_profile": "https://Stackoverflow.com/users/176728",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at this post:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1191897/how-to-check-if-pdf-was-successfully-opened-in-the-browser-using-watin/1457215#1457215\">How to check if PDF was successfully opened in the browser using WatiN?</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Can anyone provide and example of downloading a PDF file using Watin? I tried the SaveAsDialogHandler but I couldn't figure it out. Perhaps a MemoryStream could be used?
Thanks,
--jb
|
This code will do the trick. The UsedialogOnce class can be found in the WatiN.UnitTests code and will be part of the WatiN 1.3 release (which will probably be released tonigh 14 october).
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler(file.FullName);
using (new UseDialogOnce(ie.DialogWatcher, fileDownloadHandler))
{
ie.Button("exportPdfButtonId").ClickNoWait();
```
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(30);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
```
}
HTH,
Jeroen van Menen
Lead developer WatiN
|
198,279 |
<p>I am a complete beginner trying to develop for FCKeditor so please bear with me here. I have been tasked with developing a custom plugin that will allow users to browse a specific set of images that the user uploads. Essentially the user first attaches images, then uses the FCKeditor to insert those images.</p>
<p>So I have my plugin directory:</p>
<ul>
<li>lang </li>
<li>fckplugin.js </li>
<li>img.png (for the toolbar button)</li>
</ul>
<p>I am looking for some help on strategy for the custom file browser (lets call it mybrowser.asp).</p>
<p>1) Should mybrowser.asp be in the plugin directory? It is dynamic and only applies to one specific area of the site.</p>
<p>2) How should I pass the querystring to mybrowser.asp?</p>
<p>3) Any other recommendations for developing FCKeditor plugins? Any sample plugins that might be helpful to me? </p>
<p>EDIT: The querystring passed to the plugin page will be the exact same as the one on the host page. (This is a very specific plugin that will only be used in one place)</p>
|
[
{
"answer_id": 198311,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 2,
"selected": true,
"text": "<p>You don't need the lang directory unless you're planning on supporting multiple languages. But even then, I would get the plugin working in one language first.</p>\n\n<p>I would probably put mybrowser.asp in the plugin directory.</p>\n\n<p>Here's some code for fckplugin.js to get you started. </p>\n\n<pre><code>// Register the related command. \n// RegisterCommand takes the following arguments: CommandName, DialogCommand \n// FCKDialogCommand takes the following arguments: CommandName, \n// Dialog Title, Path to HTML file, Width, Height\n\nFCKCommands.RegisterCommand( \n 'MyBrowser', \n new FCKDialogCommand( \n 'My Browser', \n 'Select An Image',\n FCKPlugins.Items['MyBrowser'].Path + 'mybrowser.asp',\n 500,\n 250) \n);\n\n// Create the toolbar button. \n// FCKToolbarButton takes the following arguments: CommandName, Button Caption \n\nvar button = new FCKToolbarButton( 'MyBrowser', 'Select An Image' ) ; \nbutton.IconPath = FCKPlugins.Items['MyBrowser'].Path + 'img.png' ; \nFCKToolbarItems.RegisterItem( 'MyBrowser', button ) ; \n</code></pre>\n\n<p>Edit: I haven't tested this, but you should be able to append the querystring by doing something along these lines.</p>\n\n<pre><code> 'Select An Image',\n FCKPlugins.Items['MyBrowser'].Path + 'mybrowser.asp' + window.top.location.search,\n 500, \n</code></pre>\n"
},
{
"answer_id": 201460,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 0,
"selected": false,
"text": "<p>You might not need to write your own file browser as this functionality is built in. If you check the fckconfig.js file and search for <strong>var _FileBrowserLanguage</strong> you can specify your server language and it should hopefully use the equivalent file in the <strong>editor -> filemanager -> connectors</strong> folder.</p>\n\n<p>If you <a href=\"http://docs.fckeditor.net/\" rel=\"nofollow noreferrer\">check the docs</a> hopefully that should hopefully keep you on the right track.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285/"
] |
I am a complete beginner trying to develop for FCKeditor so please bear with me here. I have been tasked with developing a custom plugin that will allow users to browse a specific set of images that the user uploads. Essentially the user first attaches images, then uses the FCKeditor to insert those images.
So I have my plugin directory:
* lang
* fckplugin.js
* img.png (for the toolbar button)
I am looking for some help on strategy for the custom file browser (lets call it mybrowser.asp).
1) Should mybrowser.asp be in the plugin directory? It is dynamic and only applies to one specific area of the site.
2) How should I pass the querystring to mybrowser.asp?
3) Any other recommendations for developing FCKeditor plugins? Any sample plugins that might be helpful to me?
EDIT: The querystring passed to the plugin page will be the exact same as the one on the host page. (This is a very specific plugin that will only be used in one place)
|
You don't need the lang directory unless you're planning on supporting multiple languages. But even then, I would get the plugin working in one language first.
I would probably put mybrowser.asp in the plugin directory.
Here's some code for fckplugin.js to get you started.
```
// Register the related command.
// RegisterCommand takes the following arguments: CommandName, DialogCommand
// FCKDialogCommand takes the following arguments: CommandName,
// Dialog Title, Path to HTML file, Width, Height
FCKCommands.RegisterCommand(
'MyBrowser',
new FCKDialogCommand(
'My Browser',
'Select An Image',
FCKPlugins.Items['MyBrowser'].Path + 'mybrowser.asp',
500,
250)
);
// Create the toolbar button.
// FCKToolbarButton takes the following arguments: CommandName, Button Caption
var button = new FCKToolbarButton( 'MyBrowser', 'Select An Image' ) ;
button.IconPath = FCKPlugins.Items['MyBrowser'].Path + 'img.png' ;
FCKToolbarItems.RegisterItem( 'MyBrowser', button ) ;
```
Edit: I haven't tested this, but you should be able to append the querystring by doing something along these lines.
```
'Select An Image',
FCKPlugins.Items['MyBrowser'].Path + 'mybrowser.asp' + window.top.location.search,
500,
```
|
198,285 |
<p>I'm using the following code, using the <a href="http://www.sharpziplib.com/" rel="noreferrer">SharpZipLib</a> library, to add files to a .zip file, but each file is being stored with its full path. I need to only store the file, in the 'root' of the .zip file.</p>
<pre><code>string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
zipFile.BeginUpdate();
foreach (string file in files)
{
zipFile.Add(file);
}
zipFile.CommitUpdate();
}
</code></pre>
<p>I can't find anything about an option for this in the supplied documentation. As this is a very popular library, I hope someone reading this may know something.</p>
|
[
{
"answer_id": 198301,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 4,
"selected": false,
"text": "<p>How about using <a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx\" rel=\"noreferrer\">System.IO.Path.GetFileName()</a> combined with the entryName parameter of ZipFile.Add()?</p>\n\n<pre><code>string[] files = Directory.GetFiles(folderPath);\nusing (ZipFile zipFile = ZipFile.Create(zipFilePath))\n{\n zipFile.BeginUpdate();\n foreach (string file in files)\n {\n zipFile.Add(file, System.IO.Path.GetFileName(file));\n }\n zipFile.CommitUpdate();\n}\n</code></pre>\n"
},
{
"answer_id": 198302,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 2,
"selected": false,
"text": "<p>The MSDN entry for <code>Directory.GetFiles()</code> states that <em>The returned file names are appended to the supplied path parameter.</em> (<a href=\"http://msdn.microsoft.com/en-us/library/07wt70x2.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/07wt70x2.aspx</a>), so the strings you are passing to <code>zipFile.Add()</code> contain the path. </p>\n\n<p>According to the SharpZipLib documentation, there is an overload of the Add method, </p>\n\n<blockquote>\n<pre><code>public void Add(string fileName, string entryName) \nParameters:\n fileName(String) The name of the file to add.\n entryName (String) The name to use for the ZipEntry on the Zip file created.\n</code></pre>\n</blockquote>\n\n<p>Try this approach:</p>\n\n<pre><code>string[] files = Directory.GetFiles(folderPath);\nusing (ZipFile zipFile = ZipFile.Create(zipFilePath))\n{\n zipFile.BeginUpdate();\n foreach (string file in files)\n {\n zipFile.Add(file, Path.GetFileName(file));\n }\n zipFile.CommitUpdate();\n}\n</code></pre>\n"
},
{
"answer_id": 200895,
"author": "ProfK",
"author_id": 8741,
"author_profile": "https://Stackoverflow.com/users/8741",
"pm_score": 6,
"selected": true,
"text": "<p>My solution was to set the <code>NameTransform</code> object property of the <code>ZipFile</code> to a <code>ZipNameTransform</code> with its <code>TrimPrefix</code> set to the directory of the file. This causes the directory part of the entry names, which are full file paths, to be removed.</p>\n\n<pre><code>public static void ZipFolderContents(string folderPath, string zipFilePath)\n{\n string[] files = Directory.GetFiles(folderPath);\n using (ZipFile zipFile = ZipFile.Create(zipFilePath))\n {\n zipFile.NameTransform = new ZipNameTransform(folderPath);\n foreach (string file in files)\n {\n zipFile.BeginUpdate();\n zipFile.Add(file);\n zipFile.CommitUpdate();\n }\n }\n}\n</code></pre>\n\n<p>What's cool is the the NameTransform property is of type <code>INameTransform</code>, allowing customisation of the name transforms.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
I'm using the following code, using the [SharpZipLib](http://www.sharpziplib.com/) library, to add files to a .zip file, but each file is being stored with its full path. I need to only store the file, in the 'root' of the .zip file.
```
string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
zipFile.BeginUpdate();
foreach (string file in files)
{
zipFile.Add(file);
}
zipFile.CommitUpdate();
}
```
I can't find anything about an option for this in the supplied documentation. As this is a very popular library, I hope someone reading this may know something.
|
My solution was to set the `NameTransform` object property of the `ZipFile` to a `ZipNameTransform` with its `TrimPrefix` set to the directory of the file. This causes the directory part of the entry names, which are full file paths, to be removed.
```
public static void ZipFolderContents(string folderPath, string zipFilePath)
{
string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
zipFile.NameTransform = new ZipNameTransform(folderPath);
foreach (string file in files)
{
zipFile.BeginUpdate();
zipFile.Add(file);
zipFile.CommitUpdate();
}
}
}
```
What's cool is the the NameTransform property is of type `INameTransform`, allowing customisation of the name transforms.
|
198,295 |
<p>I'm setting the cookie expiration using the following code:</p>
<hr>
<pre><code>// remove existing cookies.
request.Cookies.Clear();
response.Cookies.Clear();
// ... serialize and encrypt my data ...
// now set the cookie.
HttpCookie cookie = new HttpCookie(AuthCookieName, encrypted);
cookie.Expires = DateTime.Now.Add(TimeSpan.FromHours(CookieTimeOutHours));
cookie.HttpOnly = true;
response.Cookies.Add(cookie);
// redirect to different page
</code></pre>
<hr>
<p>When I read the cookie timeout in the other page I'm getting 1/1/0001 12:00 AM. If someone can help me figure out the problem, I'll appreciate it. I'm using ASP.NET 3.5</p>
<p>ok. after reading the links from Gulzar, it appears that I cannot check cookie.Expires on the HttpRequest at all? Because the links seem to suggest that cookie.Expires is always set to DateTime.MinValue because the server can never know the actual time on the client machine? So this means I have to store the time inside the cookie myself and check it? Is my understanding correct?</p>
<p>thanks
Shankar</p>
|
[
{
"answer_id": 406205,
"author": "Shankar",
"author_id": 20818,
"author_profile": "https://Stackoverflow.com/users/20818",
"pm_score": 0,
"selected": false,
"text": "<p>The version problem discussed in the link was not helpful. Basically ASP.NET cookie sucks. I had to store the expiration date time inside the cookie myself and check it in every request.</p>\n"
},
{
"answer_id": 460990,
"author": "Andy Rose",
"author_id": 1762,
"author_profile": "https://Stackoverflow.com/users/1762",
"pm_score": 6,
"selected": false,
"text": "<p>The problem here doesn't really lie with ASP.NET but with the amount of information that is provided in the http request by browsers. The expiry date would be unobtainable regardless of the platform you are using on the server side.</p>\n\n<p>As you have summarised yourself in your question the Expires property of the HttpCookie object that is provided by the HttpRequest object is always set to 1/1/0001 12:00 AM.\nThis is because this expiry information, as well as the properties such as domain and path, are not passed by the browser to the server when it sends a request. The only cookie information that is sent is the name and value(s). Therefore cookies in the request will have default values for these 'missing' fields as they are unknown on the server side.</p>\n\n<p>I would guess the reason behind this is that the expiry, domain and path attributes of a cookie are only intended to be used by the browser when it is making a decision as to whether it should pass a cookie in a request or not and that the server is only interested in the name and value(s).</p>\n\n<p>The work around you have suggested of duplicating the expiry time as another value of the cookie is a way to get the behaviour you are looking for.</p>\n"
},
{
"answer_id": 1538727,
"author": "CallMeLaNN",
"author_id": 186334,
"author_profile": "https://Stackoverflow.com/users/186334",
"pm_score": 3,
"selected": false,
"text": "<p>At first I also disappointed why Request cookie doesn't have the actual Expires value. After debugging the http by using Fiddler2. I know that .NET was not wrong, instead, http protocol is the answer why Request cookies behaving like that.</p>\n\n<p>If you use Fiddler between your app and the browser. You can see the Response cookie sent correctly to browser with all domain, path, expires, secure and httponly. However next Request cookie in http cookie header doesn't have the expires value, it only cookie name and value. Browser responsible to send this request header and I believe that is because http protocol. The reason why is because to minimize size and web server doesn't need to check it since they actually set all the values. They should notice.</p>\n\n<p>So you no need to check the expires value on web request since you already know the date. Just, if you receive the cookie back that means the cookie is not yet expired. Once you set the expires, browser will handle the expiry. If you want to change the expires, just set the new value on the response.</p>\n\n<p>CallMeLaNN</p>\n"
},
{
"answer_id": 14237761,
"author": "drinu82",
"author_id": 1248117,
"author_profile": "https://Stackoverflow.com/users/1248117",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem when testing with an Iphone. The problem was due to the Iphone having the wrong date time set on the device, thus setting the cookie expire date to datetime.now.adddays(-1) did not expire the cookie</p>\n"
},
{
"answer_id": 31889776,
"author": "Jeff Nicholson",
"author_id": 1815399,
"author_profile": "https://Stackoverflow.com/users/1815399",
"pm_score": 2,
"selected": false,
"text": "<p>To solve this problem I add a claim to the principal which I can then read back and display the cookie expiry time to the user as follows:</p>\n\n<pre><code> public static void Configuration(IAppBuilder app)\n {\n\n app.UseCookieAuthentication(new CookieAuthenticationOptions\n {\n AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,\n LoginPath = new PathString(string.Format(\"~/Login.aspx\"),\n Provider = new CookieAuthenticationProvider\n {\n OnValidateIdentity = SetExpiryClaim \n }\n });\n\n app.MapSignalR();\n }\n\n\n private static Task SetExpiryClaim(CookieValidateIdentityContext context)\n {\n var contextExpireUtc = context.Properties.ExpiresUtc;\n\n var claimTypeName = \"contextExpireUtc\";\n var identity = context.Identity;\n\n Claim contextExpiryClaim;\n\n if (identity.HasClaim(c => c.Type == claimTypeName))\n {\n contextExpiryClaim = identity.FindFirst(claimTypeName);\n identity.RemoveClaim(contextExpiryClaim);\n }\n contextExpiryClaim = new Claim(claimTypeName, contextExpireUtc.ToString());\n context.Identity.AddClaim(contextExpiryClaim);\n\n return Task.FromResult(true);\n }\n</code></pre>\n\n<p>Then you are able to retrieve the expiry time later from the ClaimsPrinciple by</p>\n\n<pre><code> ClaimsPrincipal principle = Thread.CurrentPrincipal as ClaimsPrincipal;\n DateTime contextExpiry = principle.Claims.First(p => p.Type == \"contextExpireUtc\").Value.AsDateTime();\n</code></pre>\n"
},
{
"answer_id": 64606447,
"author": "Ali Kleit",
"author_id": 7964217,
"author_profile": "https://Stackoverflow.com/users/7964217",
"pm_score": 0,
"selected": false,
"text": "<p>A request from a browser sends only the <code>name</code> and <code>value</code> of the cookies as follows:</p>\n<pre><code>GET /sample_page.html HTTP/2.0\nHost: www.example.org\nCookie: yummy_cookie=choco; tasty_cookie=strawberry\n</code></pre>\n<p>So this is <strong>not a problem in ASP.NET</strong>. And as mentioned in some answers and comments the expiration date is to determine whether to send that cookie to the server or not. So if the cookie was expired, it would be <code>null</code> on the server.</p>\n<p>Also the workaround would be storing another value on that cookie that determines the expiry date (if you really need it)</p>\n<p>Reference: <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#The_client_sends_back_to_the_server_its_cookies_previously_stored\" rel=\"nofollow noreferrer\">Using HTTP cookies</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20818/"
] |
I'm setting the cookie expiration using the following code:
---
```
// remove existing cookies.
request.Cookies.Clear();
response.Cookies.Clear();
// ... serialize and encrypt my data ...
// now set the cookie.
HttpCookie cookie = new HttpCookie(AuthCookieName, encrypted);
cookie.Expires = DateTime.Now.Add(TimeSpan.FromHours(CookieTimeOutHours));
cookie.HttpOnly = true;
response.Cookies.Add(cookie);
// redirect to different page
```
---
When I read the cookie timeout in the other page I'm getting 1/1/0001 12:00 AM. If someone can help me figure out the problem, I'll appreciate it. I'm using ASP.NET 3.5
ok. after reading the links from Gulzar, it appears that I cannot check cookie.Expires on the HttpRequest at all? Because the links seem to suggest that cookie.Expires is always set to DateTime.MinValue because the server can never know the actual time on the client machine? So this means I have to store the time inside the cookie myself and check it? Is my understanding correct?
thanks
Shankar
|
The problem here doesn't really lie with ASP.NET but with the amount of information that is provided in the http request by browsers. The expiry date would be unobtainable regardless of the platform you are using on the server side.
As you have summarised yourself in your question the Expires property of the HttpCookie object that is provided by the HttpRequest object is always set to 1/1/0001 12:00 AM.
This is because this expiry information, as well as the properties such as domain and path, are not passed by the browser to the server when it sends a request. The only cookie information that is sent is the name and value(s). Therefore cookies in the request will have default values for these 'missing' fields as they are unknown on the server side.
I would guess the reason behind this is that the expiry, domain and path attributes of a cookie are only intended to be used by the browser when it is making a decision as to whether it should pass a cookie in a request or not and that the server is only interested in the name and value(s).
The work around you have suggested of duplicating the expiry time as another value of the cookie is a way to get the behaviour you are looking for.
|
198,312 |
<p>I'm learning how to make a firefox extension.
I have created a xul and overlay file that makes a sidebar in my browser. I'm trying to put buttons in my sidebar that load different pages within the main browser window. I'm not sure how to access the main browser window and load a new url within it. I have here a simple button and script to show you what I have so far. Any light on this subject would be greatly appreciated! </p>
<pre><code><script type="application/x-javascript">
function loadURL(url) {
// I know this part is wrong. How do I load url into main browser??
window.content.open(url)
}
</script>
<button
id="identifier"
class="dialog"
label="Yahoo"
image="images/image.jpg"
oncommand="loadURL("http://www.yahoo.com);"/>
</code></pre>
|
[
{
"answer_id": 198685,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to access active tab window context in the following way:</p>\n\n<pre>\nfunction loadURL(url) { \n content.wrappedJSObject.location = url;\n}\n</pre>\n"
},
{
"answer_id": 3382347,
"author": "esafwan",
"author_id": 363661,
"author_profile": "https://Stackoverflow.com/users/363661",
"pm_score": 0,
"selected": false,
"text": "<p>This another method!</p>\n\n<pre><code>document.getElementById('1').loadURI('http://tridz.com')\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27538/"
] |
I'm learning how to make a firefox extension.
I have created a xul and overlay file that makes a sidebar in my browser. I'm trying to put buttons in my sidebar that load different pages within the main browser window. I'm not sure how to access the main browser window and load a new url within it. I have here a simple button and script to show you what I have so far. Any light on this subject would be greatly appreciated!
```
<script type="application/x-javascript">
function loadURL(url) {
// I know this part is wrong. How do I load url into main browser??
window.content.open(url)
}
</script>
<button
id="identifier"
class="dialog"
label="Yahoo"
image="images/image.jpg"
oncommand="loadURL("http://www.yahoo.com);"/>
```
|
You should be able to access active tab window context in the following way:
```
function loadURL(url) {
content.wrappedJSObject.location = url;
}
```
|
198,320 |
<p>As far as I can understand, when I new up a <em>Linq to SQL class</em>, it is the equivalent of new'ing up a <em>SqlConnection object</em>.</p>
<p>Suppose I have an object with two methods: <code>Delete()</code> and <code>SubmitChanges()</code>. Would it be wise of me to new up the <em>Linq to SQL class</em> in each of the methods, or would a private variable holding the <em>Linq to SQL class</em> - new'ed up by the constructor - be the way to go?</p>
<p>What I'm trying to avoid is a time-out.</p>
<p><strong>UPDATE:</strong></p>
<pre><code>namespace Madtastic
{
public class Comment
{
private Boolean _isDirty = false;
private Int32 _id = 0;
private Int32 _recipeID = 0;
private String _value = "";
private Madtastic.User _user = null;
public Int32 ID
{
get
{
return this._id;
}
}
public String Value
{
get
{
return this._value;
}
set
{
this._isDirty = true;
this._value = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public Comment()
{
}
public Comment(Int32 commentID)
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (comment != null)
{
this._id = comment.CommentsID;
this._recipeID = comment.RecipesID;
this._value = comment.CommentsValue;
this._user = new User(comment.UsersID);
}
mdc.Dispose();
}
public void SubmitChanges()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null && this._isDirty)
{
comment.CommentsValue = this._value;
}
else
{
Madtastic.Entities.Comment c = new Madtastic.Entities.Comment();
c.RecipesID = this._recipeID;
c.UsersID = this._user.ID;
c.CommentsValue = this._value;
mdc.Comments.InsertOnSubmit(c);
}
mdc.SubmitChanges();
mdc.Dispose();
}
public void Delete()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null)
{
mdc.Comments.DeleteOnSubmit(comment);
mdc.SubmitChanges();
this._isDirty = false;
this._id = 0;
this._recipeID = 0;
this._value = "";
this._user = null;
}
mdc.Dispose();
}
}
}
</code></pre>
<p><strong>REFACTORED CODE (according to Grank's spec):</strong></p>
<pre><code>namespace Madtastic
{
public sealed class CommentNew : IDisposable
{
private Madtastic.DataContext _mdc;
private Madtastic.Entities.Comment _comment;
private Madtastic.User _user;
public Int32 ID
{
get
{
return this._comment.CommentsID;
}
}
public String Value
{
get
{
return this._comment.CommentsValue;
}
set
{
this._comment.CommentsValue = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public void Comment(Int32 commentID)
{
this._mdc = new Madtastic.DataContext();
this._comment = (from c in _mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (this._comment == null)
{
this._comment = new Madtastic.Entities.Comment();
this._mdc.Comments.InsertOnSubmit(this._comment);
}
else
{
this._user = new Madtastic.User(this._comment.User.UsersID);
}
}
public void SubmitChanges()
{
this._mdc.SubmitChanges();
}
public void Delete()
{
this._mdc.Comments.DeleteOnSubmit(this._comment);
this.SubmitChanges();
}
void IDisposable.Dispose()
{
this._mdc.Dispose();
}
}
}
</code></pre>
|
[
{
"answer_id": 198609,
"author": "Jacob Proffitt",
"author_id": 1336,
"author_profile": "https://Stackoverflow.com/users/1336",
"pm_score": 0,
"selected": false,
"text": "<p>I assume that you mean holding a value for the DataContext class? Personally, my preference is to default to a \"using\" clause for anything that is IDisposable (which the DataContext classes are). Instantiating in the constructor and holding a DataContext in a private variable would make that impossible. So to me, I'd put the instantiation in the methods, but more specifically, I'd put instantiation in a using clause so that proper disposal is insured.</p>\n"
},
{
"answer_id": 198647,
"author": "Grank",
"author_id": 12975,
"author_profile": "https://Stackoverflow.com/users/12975",
"pm_score": 2,
"selected": false,
"text": "<p>Depends on to what you refer by a \"LINQ-to-SQL class\", and what the code in question looks like.<br />\nIf you're talking about the DataContext object, and your code is a class with a long lifetime or your program itself, I believe it would be best to initialize it in the constructor. It's not really like creating and/or opening a new SqlConnection, it's actually very smart about managing its database connection pool and concurrency and integrity so that you don't need to think about it, that's part of the joy in my experience so far with LINQ-to-SQL. I've never seen a time-out problem occur.<br />\nOne thing you should know is that it's very difficult to share table objects across DataContext scope, and it's really not recommended if you can avoid it. Detach() and Attach() can be bitchy. So if you need to pass around a LINQ-to-SQL object that represents a row in a table on your SQL database, you should try to design the life cycle of the DataContext object to encompass all the work you need to do on any object that comes out of it. <br />\nFurthermore, there's a lot of overhead that goes into instantiating a DataContext object, and a lot of overhead that is managed by it... If you're hitting the same few tables over and over it would be best to use the same DataContext instance, as it will manage its connection pool, and in some cases cache some things for efficiency. However, it's recommended to not have every table in your database loaded into your DataContext, only the ones you need, and if the tables being accessed are very separate in very separate circumstances, you can consider splitting them into multiple DataContexts, which gives you some options on when you initialize each one if the circumstances surrounding them are different. </p>\n"
},
{
"answer_id": 198834,
"author": "Jeff Schumacher",
"author_id": 27498,
"author_profile": "https://Stackoverflow.com/users/27498",
"pm_score": 0,
"selected": false,
"text": "<p>One of my current projects uses Linq to SQL where we're holding the datacontext as a private field inside of the object. Doing so hasn't been troublesome for the most part, allows for future mocking if I pass in a datacontext in the constructor, and just seems cleaner than opening up multiple datacontexts. Similar to what Jacob mentioned above, we're implementing IDisposable to make sure that the datacontext can reliably be closed down when the object is no longer needed.</p>\n"
},
{
"answer_id": 198845,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>SqlConnections are pooled by default. You should new them up a bunch to justify that pooling cost!</p>\n\n<p>DataContexts are cheap to make (after the first). You should new them up a bunch to justify that first new-up cost!</p>\n"
},
{
"answer_id": 199159,
"author": "Grank",
"author_id": 12975,
"author_profile": "https://Stackoverflow.com/users/12975",
"pm_score": 3,
"selected": true,
"text": "<p>Having now reviewed the code sample you edited to post, I would definitely refactor your class to take advantage of LINQ-to-SQL's built in functionality. (I won't edit my previous comment because it's a better answer to the general question)<br />\nYour class's fields appear to be a pretty direct mapping of the columns on the Comments table in the database. Therefore you don't need to do most of what you're doing manually in this class. Most of the functionality could be handled by just having a private member of type Madtastic.Entities.Comment (and just mapping your properties to its properties if you have to maintain how this class interacts with the rest of the project). Then your constructor can just initialize a private member Madtastic.DataContext and set your private member Madtastic.Entities.Comment to the result of the LINQ query on it. If the comment is null, create a new one and call InsertOnSubmit on the DataContext. (but it doesn't make sense to submit changes yet because you haven't set any values for this new object anyway)<br />\nIn your SubmitChanges, all you should have to do is call SubmitChanges on the DataContext. It keeps its own track of whether or not the data needs to be updated, it won't hit the database if it doesn't, so you don't need _isDirty.<br />\nIn your Delete(), all you should have to do is call DeleteOnSubmit on the DataContext.<br />\nYou may in fact find with a little review that you don't need the Madtastic.Comment class at all, and the Madtastic.Entities.Comment LINQ-to-SQL class can act directly as your data access layer. It seems like the only practical differences are the constructor that takes a commentID, and the fact that the Entities.Comment has a UsersID property where your Madtastic.Comment class has a whole User. (However, if User is also a table in the database, and UsersID is a foreign key to its primary key, you'll find that LINQ-to-SQL has created a User object on the Entities.Comment object that you can access directly with comment.User)<br />\nIf you find you can eliminate this class entirely, it might mean that you can further optimize your DataContext's life cycle by bubbling it up to the methods in your project that make use of Comment.</p>\n\n<p>Edited to post the following example refactored code (apologies for any errors, as I typed it in notepad in a couple seconds rather than opening visual studio, and I wouldn't get intellisense for your project anyway):</p>\n\n<pre><code>namespace Madtastic\n{\n public class Comment\n {\n private Madtastic.DataContext mdc;\n private Madtastic.Entities.Comment comment;\n\n public Int32 ID\n {\n get\n {\n return comment.CommentsID;\n }\n }\n\n public Madtastic.User Owner\n {\n get\n {\n return comment.User;\n }\n }\n\n public Comment(Int32 commentID)\n { \n mdc = new Madtastic.DataContext();\n\n comment = (from c in mdc.Comments\n where c.CommentsID == commentID\n select c).FirstOrDefault();\n\n if (comment == null)\n {\n comment = new Madtastic.Entities.Comment();\n mdc.Comments.InsertOnSubmit(comment);\n }\n\n }\n\n public void SubmitChanges()\n {\n\n mdc.SubmitChanges();\n\n }\n\n\n public void Delete()\n {\n mdc.Comments.DeleteOnSubmit(comment);\n SubmitChanges();\n }\n }\n}\n</code></pre>\n\n<p>You will probably also want to implement IDisposable/using as a number of people have suggested.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
As far as I can understand, when I new up a *Linq to SQL class*, it is the equivalent of new'ing up a *SqlConnection object*.
Suppose I have an object with two methods: `Delete()` and `SubmitChanges()`. Would it be wise of me to new up the *Linq to SQL class* in each of the methods, or would a private variable holding the *Linq to SQL class* - new'ed up by the constructor - be the way to go?
What I'm trying to avoid is a time-out.
**UPDATE:**
```
namespace Madtastic
{
public class Comment
{
private Boolean _isDirty = false;
private Int32 _id = 0;
private Int32 _recipeID = 0;
private String _value = "";
private Madtastic.User _user = null;
public Int32 ID
{
get
{
return this._id;
}
}
public String Value
{
get
{
return this._value;
}
set
{
this._isDirty = true;
this._value = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public Comment()
{
}
public Comment(Int32 commentID)
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (comment != null)
{
this._id = comment.CommentsID;
this._recipeID = comment.RecipesID;
this._value = comment.CommentsValue;
this._user = new User(comment.UsersID);
}
mdc.Dispose();
}
public void SubmitChanges()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null && this._isDirty)
{
comment.CommentsValue = this._value;
}
else
{
Madtastic.Entities.Comment c = new Madtastic.Entities.Comment();
c.RecipesID = this._recipeID;
c.UsersID = this._user.ID;
c.CommentsValue = this._value;
mdc.Comments.InsertOnSubmit(c);
}
mdc.SubmitChanges();
mdc.Dispose();
}
public void Delete()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null)
{
mdc.Comments.DeleteOnSubmit(comment);
mdc.SubmitChanges();
this._isDirty = false;
this._id = 0;
this._recipeID = 0;
this._value = "";
this._user = null;
}
mdc.Dispose();
}
}
}
```
**REFACTORED CODE (according to Grank's spec):**
```
namespace Madtastic
{
public sealed class CommentNew : IDisposable
{
private Madtastic.DataContext _mdc;
private Madtastic.Entities.Comment _comment;
private Madtastic.User _user;
public Int32 ID
{
get
{
return this._comment.CommentsID;
}
}
public String Value
{
get
{
return this._comment.CommentsValue;
}
set
{
this._comment.CommentsValue = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public void Comment(Int32 commentID)
{
this._mdc = new Madtastic.DataContext();
this._comment = (from c in _mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (this._comment == null)
{
this._comment = new Madtastic.Entities.Comment();
this._mdc.Comments.InsertOnSubmit(this._comment);
}
else
{
this._user = new Madtastic.User(this._comment.User.UsersID);
}
}
public void SubmitChanges()
{
this._mdc.SubmitChanges();
}
public void Delete()
{
this._mdc.Comments.DeleteOnSubmit(this._comment);
this.SubmitChanges();
}
void IDisposable.Dispose()
{
this._mdc.Dispose();
}
}
}
```
|
Having now reviewed the code sample you edited to post, I would definitely refactor your class to take advantage of LINQ-to-SQL's built in functionality. (I won't edit my previous comment because it's a better answer to the general question)
Your class's fields appear to be a pretty direct mapping of the columns on the Comments table in the database. Therefore you don't need to do most of what you're doing manually in this class. Most of the functionality could be handled by just having a private member of type Madtastic.Entities.Comment (and just mapping your properties to its properties if you have to maintain how this class interacts with the rest of the project). Then your constructor can just initialize a private member Madtastic.DataContext and set your private member Madtastic.Entities.Comment to the result of the LINQ query on it. If the comment is null, create a new one and call InsertOnSubmit on the DataContext. (but it doesn't make sense to submit changes yet because you haven't set any values for this new object anyway)
In your SubmitChanges, all you should have to do is call SubmitChanges on the DataContext. It keeps its own track of whether or not the data needs to be updated, it won't hit the database if it doesn't, so you don't need \_isDirty.
In your Delete(), all you should have to do is call DeleteOnSubmit on the DataContext.
You may in fact find with a little review that you don't need the Madtastic.Comment class at all, and the Madtastic.Entities.Comment LINQ-to-SQL class can act directly as your data access layer. It seems like the only practical differences are the constructor that takes a commentID, and the fact that the Entities.Comment has a UsersID property where your Madtastic.Comment class has a whole User. (However, if User is also a table in the database, and UsersID is a foreign key to its primary key, you'll find that LINQ-to-SQL has created a User object on the Entities.Comment object that you can access directly with comment.User)
If you find you can eliminate this class entirely, it might mean that you can further optimize your DataContext's life cycle by bubbling it up to the methods in your project that make use of Comment.
Edited to post the following example refactored code (apologies for any errors, as I typed it in notepad in a couple seconds rather than opening visual studio, and I wouldn't get intellisense for your project anyway):
```
namespace Madtastic
{
public class Comment
{
private Madtastic.DataContext mdc;
private Madtastic.Entities.Comment comment;
public Int32 ID
{
get
{
return comment.CommentsID;
}
}
public Madtastic.User Owner
{
get
{
return comment.User;
}
}
public Comment(Int32 commentID)
{
mdc = new Madtastic.DataContext();
comment = (from c in mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (comment == null)
{
comment = new Madtastic.Entities.Comment();
mdc.Comments.InsertOnSubmit(comment);
}
}
public void SubmitChanges()
{
mdc.SubmitChanges();
}
public void Delete()
{
mdc.Comments.DeleteOnSubmit(comment);
SubmitChanges();
}
}
}
```
You will probably also want to implement IDisposable/using as a number of people have suggested.
|
198,322 |
<p>Let's say I'm working on a little batch-processing console app in VB.Net. I want to be able to structure the app like this:</p>
<pre class="lang-vb prettyprint-override"><code>Sub WorkerMethod()
'Do some work
Trace.WriteLine("Work progress")
'Do more work
Trace.WriteLine("Another progress update")
'...
End Sub
Sub Main()
'Do any setup, like confirm the user wants to continue or whatever
WorkerMethod()
End Sub
</code></pre>
<p>Note that I'm using <code>Trace</code> rather than <code>Console</code> for my output. This is because the worker method may be called from elsewhere, or even live in a different assembly, and I want to be able to attach different trace listeners to it. So how can I connect the console to the trace? </p>
<p>I can already do it by defining a simple class (shown below) and adding an instance to the Trace's listeners collection, but I'm wondering if there's a more accepted or built in way to accomplish this:</p>
<pre class="lang-vb prettyprint-override"><code>Public Class ConsoleTrace
Inherits Diagnostics.TraceListener
Public Overloads Overrides Sub Write(ByVal message As String)
Console.Write(message)
End Sub
Public Overloads Overrides Sub WriteLine(ByVal message As String)
Console.WriteLine(message)
End Sub
End Class
</code></pre>
|
[
{
"answer_id": 198326,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 8,
"selected": true,
"text": "<p>You can add the following to your exe's .config file.</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<configuration>\n <system.diagnostics>\n <trace autoflush=\"true\">\n <listeners>\n <add name=\"logListener\" type=\"System.Diagnostics.TextWriterTraceListener\" initializeData=\"cat.log\" />\n <add name=\"consoleListener\" type=\"System.Diagnostics.ConsoleTraceListener\"/>\n </listeners>\n </trace>\n </system.diagnostics>\n</configuration>\n</code></pre>\n\n<p>I included the TextWriter as well, in case you're interested in logging to a file.</p>\n"
},
{
"answer_id": 863832,
"author": "Scott Marlowe",
"author_id": 1683,
"author_profile": "https://Stackoverflow.com/users/1683",
"pm_score": 4,
"selected": false,
"text": "<p>Great solution, but I have a situation where I have different dll's being run by the same calling exe, so I don't want to modify the calling exe's .config file. I want each dll to handle it's own alteration of the trace output.</p>\n\n<p>Easy enough:</p>\n\n<pre><code>Stream outResultsFile = File.Create (\"output.txt\");\nvar textListener = new TextWriterTraceListener (outResultsFile);\nTrace.Listeners.Add (textListener);\n</code></pre>\n\n<p>This will, of course, output Trace output to the \"output.txt\" file.</p>\n"
},
{
"answer_id": 1614253,
"author": "Scott P",
"author_id": 33848,
"author_profile": "https://Stackoverflow.com/users/33848",
"pm_score": 6,
"selected": false,
"text": "<p>Joel,</p>\n\n<p>You could do this instead of the app config method:</p>\n\n<pre><code>Trace.Listeners.Add(new ConsoleTraceListener());\n</code></pre>\n\n<p>or this, if you want to manage adding or removing the listener during the life of the app:</p>\n\n<pre><code>ConsoleTraceListener listener = new ConsoleTraceListener();\nTrace.Listeners.Add(listener);\n\nTrace.WriteLine(\"Howdy\");\n\nTrace.Listeners.Remove(listener);\n\nTrace.Close();\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
Let's say I'm working on a little batch-processing console app in VB.Net. I want to be able to structure the app like this:
```vb
Sub WorkerMethod()
'Do some work
Trace.WriteLine("Work progress")
'Do more work
Trace.WriteLine("Another progress update")
'...
End Sub
Sub Main()
'Do any setup, like confirm the user wants to continue or whatever
WorkerMethod()
End Sub
```
Note that I'm using `Trace` rather than `Console` for my output. This is because the worker method may be called from elsewhere, or even live in a different assembly, and I want to be able to attach different trace listeners to it. So how can I connect the console to the trace?
I can already do it by defining a simple class (shown below) and adding an instance to the Trace's listeners collection, but I'm wondering if there's a more accepted or built in way to accomplish this:
```vb
Public Class ConsoleTrace
Inherits Diagnostics.TraceListener
Public Overloads Overrides Sub Write(ByVal message As String)
Console.Write(message)
End Sub
Public Overloads Overrides Sub WriteLine(ByVal message As String)
Console.WriteLine(message)
End Sub
End Class
```
|
You can add the following to your exe's .config file.
```
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="logListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="cat.log" />
<add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>
```
I included the TextWriter as well, in case you're interested in logging to a file.
|
198,337 |
<p>When hiring a front-end developer, what specific skills and practices should you test for? What is a good metric for evaluating their skill in HTML, CSS and Javascript?</p>
<p>Obviously, table-less semantic HTML and pure CSS layout are probably the key skills. But what about specific techniques? Should he/she be able to effortlessly mock up a multi-column layout? CSS sprites? Equal height (or faux) columns? Does HTML tag choice matter (ie, relying too heavily on <code><div></code>)? Should they be able to explain (in words) how floats work?</p>
<p>And what about javascript skills? How important is framework experience (jQuery, Prototype, etc). today?</p>
<p>Obviously, the details of the position and the sites they'll be working on are the best indication of what skills are needed. But I'm wondering what specific skills people might consider to be deal-breakers (or makers) when creating tests for candidates. </p>
|
[
{
"answer_id": 198344,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "<p>I wouldn't put too much weight on it, as proper HTML/CSS is so simple that anyone can learn it in a week.</p>\n\n<p>That said, you might want to review their portfolio to help you make a decision on their current skill level.</p>\n"
},
{
"answer_id": 198347,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Ask for a portfolio, and then review it with your team. That takes care of posers and people who \"don't handle interviews well.\"</p>\n\n<p>Other than that, I'd present them with something relatively simple to mock up and a laptop and say 'have at it.'</p>\n\n<p>Maybe ask them what they like most about web design today, and what they hate the most. Ask them about their opinions about what is on the horizon (HTML 5, IE 8, Chrome, etc) to see if they keep abreast of what's coming out.</p>\n\n<p>Ask them if they have a favorite JavaScript framework and why. Maybe have them code something in JS a la the [in]famous fizz buzz problem.</p>\n"
},
{
"answer_id": 198354,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 5,
"selected": true,
"text": "<p>When I interview people for a position of Client-Side developer I try to figure out:</p>\n\n<pre>\n1) Understanding DOM (what is that, how is it related to HTML etc)\n2) Understanding XML/namespaces\n3) Understanding JavaScript (object-oriented? what otherwise)\n4) Knowing approaches to componentization (XBL, HTC) - plus\n5) Understanding OO principles\n6) JavaScript closures\n7) Memory leaks in browsers\n</pre>\n\n<p>The only simple test case I give right away:</p>\n\n<pre>\n<script type=\"text/javascript\">\nvar a = 1;\n</script>\n</pre>\n\n<p>I suggest interviewee to explain in technical terms that line.</p>\n\n<p>And I also check on overall awareness of the current state of the Web technologies, among other questions I suggest designing a web-browser where interviewee is suggested to pick technologies he would put into his brand-new creature, suggest ones that might be missing from the current client-side platform.</p>\n"
},
{
"answer_id": 198481,
"author": "Anjisan",
"author_id": 25304,
"author_profile": "https://Stackoverflow.com/users/25304",
"pm_score": 3,
"selected": false,
"text": "<p>Sergey and swilliams both gave great answers, in particular, swilliams mention of asking for a portfolio is key. With a portfolio you can also test for items like,</p>\n\n<ul>\n<li>does the html and css validate?</li>\n<li>does the presentation render consistent across browsers?</li>\n<li>does the candidate have JavaScript errors? if they do, does the person let them bubble up to the presentation layer or do they at least catch them with a try/catch block?</li>\n<li>in terms of JS, how advanced is the person? Can they do form validation? Can they do regex? Are they relying on MM_Preloader? (Yuck!)</li>\n</ul>\n\n<p>A portfolio can also give a sense of how passionate someone is about web development. Moreover, if they've done a site for someone else, that alone presents an opportunity to talk about a number of things with a candidate,</p>\n\n<ul>\n<li>how did they go about developing the UI?</li>\n<li>what kind of planning went into the site?</li>\n<li>how were user expectations uncovered/met?</li>\n<li>what kind of challenges during construction came into play? </li>\n</ul>\n\n<p>Beyond these items, one other approach you might want to consider is a developer test that you could send a prospective hire. Nothing too hard that would take more than a day, but enough of a brain teaser to see if they can work through a CSS or JS problem. </p>\n"
},
{
"answer_id": 198783,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": -1,
"selected": false,
"text": "<p>I know this isn't a great answer, but one of the first things I do is expose the formatting of their Word resume. If they've made use of the indents and styles that Word offers and it's not tab, tab, tab, space, space, space, space then they go top of the pile.</p>\n"
},
{
"answer_id": 199157,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": -1,
"selected": false,
"text": "<p>\"</p>\n\n<p>Obviously, table-less semantic HTML and pure CSS layout are probably the key skills.</p>\n\n<p>\"</p>\n\n<p>I don't understand that sentence ...</p>\n\n<p>Do you really mean that it is better to do what is a simple task using tables in a complicated manner just to avoid using tables ?-)</p>\n\n<p>Table-o-phobia is just as hard a disease as making large-scale websites without serverside assistance ...</p>\n\n<p>Of course the table-hells of the last decade isn't interesting, but a lot of tasks is really stupid to complete without using tables ...</p>\n\n<p>Use the html-element which easyist completes the task, no matter which tagnames it uses !-)</p>\n\n<p>-- and I don't understand what a 'pure css-layout' is; I never figured out how to create an html-page without html-elements to host the layout in the stylesheet ...</p>\n"
},
{
"answer_id": 199169,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 1,
"selected": false,
"text": "<p>An understanding of how browsers are different is also key. Especially IE. If they have only ever coded for IE beware! Vica Versa too, if they've never tested their stuff in IE6/7 they have no idea how horribly it is failing.</p>\n\n<p>If they can name 3 things that fail, or need workarounds for in IE, then they're likely on the ball. If they can't, they haven't had enough cross browser experience yet.</p>\n"
},
{
"answer_id": 199170,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for all you're answers so far. They're definitely good advice. I'm not ready to mark one as accepted though. What I was really looking for were concrete tasks that a front-end developers need to be able to produce in a test environment. In other words, what is FizzBuzz for CSS?</p>\n\n<p>I do agree that a solid portfolio and the ability to speak intelligently about the subject will probably minimize the importance of a test. On the other hand, I think we all know candidates who are very good at talking big, but when it comes down to actually demonstrating practical knowledge, they fall short.</p>\n\n<p>@JonathanHolland - I tend to disagree. HTML/CSS is certainly easily learned, but the knowledge gained from a few quick tutorials is nothing compared to someone who has spent years doing layout. There are lots of techniques and practices that a good CSS dev can bring to the table.</p>\n\n<p>@roenving - Perhaps I was redundant. By \"pure-css\", I meant table-less. I also meant table-less in the sense of not using tables as a layout methodology. However, this is not the question for a div-vs-table layout discussion. Try <a href=\"https://stackoverflow.com/questions/83073/div-vs-table\">here</a>. Although I believe that most employers these days are going to be asking if a dev can do layout without the use of tables (as a methodology).</p>\n"
},
{
"answer_id": 199805,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 1,
"selected": false,
"text": "<p>I ask people what tools they use, how they code, i.e. do they use DreamWeaver, BBEdit, emacs or whatever. Assuming they don't just give a one-word answer, you normally get some kind of idea what their priorities are, how they code, etc.</p>\n\n<p>Then I ask how they validate their code, which is always interesting.</p>\n\n<p>Aside from actually testing them by having them sit down and hammer out a page, I would ask them for specific examples of work they've done, how they've resolved an issue.</p>\n\n<p>For instance, you say <em>\"tell us about a job where you were on a strict deadline\"</em> or you say <em>\"tell us about a really frustrating problem and how you overcame it\"</em> or <em>\"in the work you've done recently, what's the thing you're most proud of?\"</em></p>\n\n<p>That way you get a lot of insight into the kind of thing they've done, their problem-solving skills and experience, the way they handle stress and frustration, and of course, whether their workarounds/corner-cutting measures are smart or dumb.</p>\n"
},
{
"answer_id": 199871,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 2,
"selected": false,
"text": "<p>We used to either set up a small brief for them to work within a certain timeframe, or in some cases contract a job to them and see how they went. </p>\n\n<p>I was never that worried about making someone sit down at a laptop in an interview room and bang out a solution, because that kind of environment is not (you'd hope) very much like the normal working conditions. </p>\n\n<p>The exact nature of the brief will depend a lot on the skillset you are looking for. In some shops, the front end developers will have to take on a certain amount of filling the gaps in design, and/or performing \"brand police\" duties as they implement the design \"vibe\".<br>\nIn those cases, leaving some holes in the brief regarding some of the finer points of the typography and other small details can give you some hints as to their abilities in those respects.<br>\nLet them choose the javascript framework, did they choose the one best for the job, or the one that they knew. (subjective question, yes. But pulling in dojo for the sake of a datepicker and some menu animations might be overkill) </p>\n\n<p>I would look for someone who can implement css based layouts, but can in fact work on table based layouts if needed when dealing with legacy projects. Maligned as they are, some of the finer details of hacky table layouts weren't always easy. </p>\n\n<p>The main thing in this sort of task is the attention to detail, have they added a set of style rules for printing, used appropriate image sizing and formats, produced clean and valid code, have they gone for gold because they really want the job, and are prepared to stretch themselves a little to get it. </p>\n\n<p>Because you give them some extra time, it is fair to expect that they try to impress, rather than the stress laden scenario of putting them at a strange desk and telling them to go for it. So, whilst being realistic and not expecting obsessively perfect work every day on every task, in this situation I'm looking for gold, or at least evidence that gold was the target.</p>\n\n<p>Throw in a curve ball of something they haven't done before... see how well they can pick it up in a hurry. Experience is good, but the ability to learn fast is probably more important in an area that changes so fast.</p>\n"
},
{
"answer_id": 200149,
"author": "Martin Kool",
"author_id": 216896,
"author_profile": "https://Stackoverflow.com/users/216896",
"pm_score": 2,
"selected": false,
"text": "<p>At my company we don't work with tests and the portfolio is more important, especially because we tend to look at the candidate's personal motivation and passion for doing front-end development.</p>\n\n<p>But if I should give the candidate a test before hiring, I would go about it this way:</p>\n\n<p>Hand over a print-out of a photoshopped web page representing a clear semantic component tree underneath. Ask the person how he or she would come to a result in html. Just ask him or her to think out loud. What goes through one's head when seeing a page, knowing it needs to be developed. </p>\n\n<p>Then it comes down to the approach the candidate takes.</p>\n\n<p>Choosing the best available markup for each specific html section is one (important) aspect, but can be mastered with experienced people around to guide a new employee. Being able to properly break down a design into its semantic components, identifying sections and separating primary and secondary content from navigation is not math or science and therefore hard to test. But a conversation about the approach of breaking down a page might separate experienced people from beginners.</p>\n\n<p>But as I said in my first line, we usually ask for what kind of web-related work a person has done in his or her free time, such as a blog, game or demo. If done anything, the person usually was really good at front-end development or was eager to learn and adapt.</p>\n"
},
{
"answer_id": 305689,
"author": "Mike B",
"author_id": 3609,
"author_profile": "https://Stackoverflow.com/users/3609",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have any experience with hiring, but I've attended a number of Web Developer interviews and can relate my experiences.</p>\n\n<p>Out of all my interviews one method really stuck out as the best way of discovering true talent. I'll admit that I'm no expert, and this is probably why I didn't get the job, but this was a fantastic way of weeding out those that were capable and those that were great.</p>\n\n<p>We were asked a couple of questions about DOM, Object-Orientation, Closures, XML Namespaces and general Web Design, then we were taken into a quiet office with a nice view across the nearby river and asked to write a few examples to show our ability. We were left alone, but were told that the source code and our browser history would be viewed after, if we needed to use a browser. We were asked to make a company intranet using the following:</p>\n\n<ul>\n<li>A simple three column layout</li>\n<li>A good-looking table using CSS</li>\n<li>A usable but good-looking Navigation Bar.</li>\n<li>Dynamic loading using XML and JavaScript</li>\n</ul>\n\n<p>Given a small amount of time to do this, you get to see people that can really do this stuff. Whilst perhaps their example could always be better or more suited to different applications it just goes to show that the best way to show the skill of a developer is to <strong>get them to make something!</strong> If you know your stuff and they know their stuff their code will be good.</p>\n"
},
{
"answer_id": 14874465,
"author": "Vadim",
"author_id": 2071785,
"author_profile": "https://Stackoverflow.com/users/2071785",
"pm_score": 3,
"selected": false,
"text": "<p>I can suggest you online test, that includes HTML, CSS and JavaScript together.</p>\n\n<p><a href=\"http://tests4geeks.com/test/html-css-javascript\" rel=\"nofollow\">http://tests4geeks.com/test/html-css-javascript</a></p>\n\n<p>It has 60 questions (20 for each subject). And you will recieve the report via email, when the candidate finishes the test.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4636/"
] |
When hiring a front-end developer, what specific skills and practices should you test for? What is a good metric for evaluating their skill in HTML, CSS and Javascript?
Obviously, table-less semantic HTML and pure CSS layout are probably the key skills. But what about specific techniques? Should he/she be able to effortlessly mock up a multi-column layout? CSS sprites? Equal height (or faux) columns? Does HTML tag choice matter (ie, relying too heavily on `<div>`)? Should they be able to explain (in words) how floats work?
And what about javascript skills? How important is framework experience (jQuery, Prototype, etc). today?
Obviously, the details of the position and the sites they'll be working on are the best indication of what skills are needed. But I'm wondering what specific skills people might consider to be deal-breakers (or makers) when creating tests for candidates.
|
When I interview people for a position of Client-Side developer I try to figure out:
```
1) Understanding DOM (what is that, how is it related to HTML etc)
2) Understanding XML/namespaces
3) Understanding JavaScript (object-oriented? what otherwise)
4) Knowing approaches to componentization (XBL, HTC) - plus
5) Understanding OO principles
6) JavaScript closures
7) Memory leaks in browsers
```
The only simple test case I give right away:
```
<script type="text/javascript">
var a = 1;
</script>
```
I suggest interviewee to explain in technical terms that line.
And I also check on overall awareness of the current state of the Web technologies, among other questions I suggest designing a web-browser where interviewee is suggested to pick technologies he would put into his brand-new creature, suggest ones that might be missing from the current client-side platform.
|
198,341 |
<p>I would like to create a window with a progressbar which shows the current status of Spring's object instantiation. From Spring.Net's <a href="http://www.springframework.net/docs/1.1.2/reference/html/objects.html#objects-factory-customizing" rel="nofollow noreferrer">documentation</a> it seems that <code>IObjectPostProcessors</code> is the right point to start and track whenever an Object has been instanciated. However in order to get "Percentage of instantiated classes" I need to ask <code>ObjectDefinitionCount</code> of spring's factory to get the number of configured object. However this does not work until the contextcreation has been finished (also <a href="https://stackoverflow.com/questions/179140/how-do-i-find-out-when-the-springnet-root-context-has-loaded">this problem</a> problem seems to be related).</p>
<p>If it's not possible to use Spring to get the start-up status, how do you display information during application start up to the user?</p>
|
[
{
"answer_id": 198344,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "<p>I wouldn't put too much weight on it, as proper HTML/CSS is so simple that anyone can learn it in a week.</p>\n\n<p>That said, you might want to review their portfolio to help you make a decision on their current skill level.</p>\n"
},
{
"answer_id": 198347,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Ask for a portfolio, and then review it with your team. That takes care of posers and people who \"don't handle interviews well.\"</p>\n\n<p>Other than that, I'd present them with something relatively simple to mock up and a laptop and say 'have at it.'</p>\n\n<p>Maybe ask them what they like most about web design today, and what they hate the most. Ask them about their opinions about what is on the horizon (HTML 5, IE 8, Chrome, etc) to see if they keep abreast of what's coming out.</p>\n\n<p>Ask them if they have a favorite JavaScript framework and why. Maybe have them code something in JS a la the [in]famous fizz buzz problem.</p>\n"
},
{
"answer_id": 198354,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 5,
"selected": true,
"text": "<p>When I interview people for a position of Client-Side developer I try to figure out:</p>\n\n<pre>\n1) Understanding DOM (what is that, how is it related to HTML etc)\n2) Understanding XML/namespaces\n3) Understanding JavaScript (object-oriented? what otherwise)\n4) Knowing approaches to componentization (XBL, HTC) - plus\n5) Understanding OO principles\n6) JavaScript closures\n7) Memory leaks in browsers\n</pre>\n\n<p>The only simple test case I give right away:</p>\n\n<pre>\n<script type=\"text/javascript\">\nvar a = 1;\n</script>\n</pre>\n\n<p>I suggest interviewee to explain in technical terms that line.</p>\n\n<p>And I also check on overall awareness of the current state of the Web technologies, among other questions I suggest designing a web-browser where interviewee is suggested to pick technologies he would put into his brand-new creature, suggest ones that might be missing from the current client-side platform.</p>\n"
},
{
"answer_id": 198481,
"author": "Anjisan",
"author_id": 25304,
"author_profile": "https://Stackoverflow.com/users/25304",
"pm_score": 3,
"selected": false,
"text": "<p>Sergey and swilliams both gave great answers, in particular, swilliams mention of asking for a portfolio is key. With a portfolio you can also test for items like,</p>\n\n<ul>\n<li>does the html and css validate?</li>\n<li>does the presentation render consistent across browsers?</li>\n<li>does the candidate have JavaScript errors? if they do, does the person let them bubble up to the presentation layer or do they at least catch them with a try/catch block?</li>\n<li>in terms of JS, how advanced is the person? Can they do form validation? Can they do regex? Are they relying on MM_Preloader? (Yuck!)</li>\n</ul>\n\n<p>A portfolio can also give a sense of how passionate someone is about web development. Moreover, if they've done a site for someone else, that alone presents an opportunity to talk about a number of things with a candidate,</p>\n\n<ul>\n<li>how did they go about developing the UI?</li>\n<li>what kind of planning went into the site?</li>\n<li>how were user expectations uncovered/met?</li>\n<li>what kind of challenges during construction came into play? </li>\n</ul>\n\n<p>Beyond these items, one other approach you might want to consider is a developer test that you could send a prospective hire. Nothing too hard that would take more than a day, but enough of a brain teaser to see if they can work through a CSS or JS problem. </p>\n"
},
{
"answer_id": 198783,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": -1,
"selected": false,
"text": "<p>I know this isn't a great answer, but one of the first things I do is expose the formatting of their Word resume. If they've made use of the indents and styles that Word offers and it's not tab, tab, tab, space, space, space, space then they go top of the pile.</p>\n"
},
{
"answer_id": 199157,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": -1,
"selected": false,
"text": "<p>\"</p>\n\n<p>Obviously, table-less semantic HTML and pure CSS layout are probably the key skills.</p>\n\n<p>\"</p>\n\n<p>I don't understand that sentence ...</p>\n\n<p>Do you really mean that it is better to do what is a simple task using tables in a complicated manner just to avoid using tables ?-)</p>\n\n<p>Table-o-phobia is just as hard a disease as making large-scale websites without serverside assistance ...</p>\n\n<p>Of course the table-hells of the last decade isn't interesting, but a lot of tasks is really stupid to complete without using tables ...</p>\n\n<p>Use the html-element which easyist completes the task, no matter which tagnames it uses !-)</p>\n\n<p>-- and I don't understand what a 'pure css-layout' is; I never figured out how to create an html-page without html-elements to host the layout in the stylesheet ...</p>\n"
},
{
"answer_id": 199169,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 1,
"selected": false,
"text": "<p>An understanding of how browsers are different is also key. Especially IE. If they have only ever coded for IE beware! Vica Versa too, if they've never tested their stuff in IE6/7 they have no idea how horribly it is failing.</p>\n\n<p>If they can name 3 things that fail, or need workarounds for in IE, then they're likely on the ball. If they can't, they haven't had enough cross browser experience yet.</p>\n"
},
{
"answer_id": 199170,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for all you're answers so far. They're definitely good advice. I'm not ready to mark one as accepted though. What I was really looking for were concrete tasks that a front-end developers need to be able to produce in a test environment. In other words, what is FizzBuzz for CSS?</p>\n\n<p>I do agree that a solid portfolio and the ability to speak intelligently about the subject will probably minimize the importance of a test. On the other hand, I think we all know candidates who are very good at talking big, but when it comes down to actually demonstrating practical knowledge, they fall short.</p>\n\n<p>@JonathanHolland - I tend to disagree. HTML/CSS is certainly easily learned, but the knowledge gained from a few quick tutorials is nothing compared to someone who has spent years doing layout. There are lots of techniques and practices that a good CSS dev can bring to the table.</p>\n\n<p>@roenving - Perhaps I was redundant. By \"pure-css\", I meant table-less. I also meant table-less in the sense of not using tables as a layout methodology. However, this is not the question for a div-vs-table layout discussion. Try <a href=\"https://stackoverflow.com/questions/83073/div-vs-table\">here</a>. Although I believe that most employers these days are going to be asking if a dev can do layout without the use of tables (as a methodology).</p>\n"
},
{
"answer_id": 199805,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 1,
"selected": false,
"text": "<p>I ask people what tools they use, how they code, i.e. do they use DreamWeaver, BBEdit, emacs or whatever. Assuming they don't just give a one-word answer, you normally get some kind of idea what their priorities are, how they code, etc.</p>\n\n<p>Then I ask how they validate their code, which is always interesting.</p>\n\n<p>Aside from actually testing them by having them sit down and hammer out a page, I would ask them for specific examples of work they've done, how they've resolved an issue.</p>\n\n<p>For instance, you say <em>\"tell us about a job where you were on a strict deadline\"</em> or you say <em>\"tell us about a really frustrating problem and how you overcame it\"</em> or <em>\"in the work you've done recently, what's the thing you're most proud of?\"</em></p>\n\n<p>That way you get a lot of insight into the kind of thing they've done, their problem-solving skills and experience, the way they handle stress and frustration, and of course, whether their workarounds/corner-cutting measures are smart or dumb.</p>\n"
},
{
"answer_id": 199871,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 2,
"selected": false,
"text": "<p>We used to either set up a small brief for them to work within a certain timeframe, or in some cases contract a job to them and see how they went. </p>\n\n<p>I was never that worried about making someone sit down at a laptop in an interview room and bang out a solution, because that kind of environment is not (you'd hope) very much like the normal working conditions. </p>\n\n<p>The exact nature of the brief will depend a lot on the skillset you are looking for. In some shops, the front end developers will have to take on a certain amount of filling the gaps in design, and/or performing \"brand police\" duties as they implement the design \"vibe\".<br>\nIn those cases, leaving some holes in the brief regarding some of the finer points of the typography and other small details can give you some hints as to their abilities in those respects.<br>\nLet them choose the javascript framework, did they choose the one best for the job, or the one that they knew. (subjective question, yes. But pulling in dojo for the sake of a datepicker and some menu animations might be overkill) </p>\n\n<p>I would look for someone who can implement css based layouts, but can in fact work on table based layouts if needed when dealing with legacy projects. Maligned as they are, some of the finer details of hacky table layouts weren't always easy. </p>\n\n<p>The main thing in this sort of task is the attention to detail, have they added a set of style rules for printing, used appropriate image sizing and formats, produced clean and valid code, have they gone for gold because they really want the job, and are prepared to stretch themselves a little to get it. </p>\n\n<p>Because you give them some extra time, it is fair to expect that they try to impress, rather than the stress laden scenario of putting them at a strange desk and telling them to go for it. So, whilst being realistic and not expecting obsessively perfect work every day on every task, in this situation I'm looking for gold, or at least evidence that gold was the target.</p>\n\n<p>Throw in a curve ball of something they haven't done before... see how well they can pick it up in a hurry. Experience is good, but the ability to learn fast is probably more important in an area that changes so fast.</p>\n"
},
{
"answer_id": 200149,
"author": "Martin Kool",
"author_id": 216896,
"author_profile": "https://Stackoverflow.com/users/216896",
"pm_score": 2,
"selected": false,
"text": "<p>At my company we don't work with tests and the portfolio is more important, especially because we tend to look at the candidate's personal motivation and passion for doing front-end development.</p>\n\n<p>But if I should give the candidate a test before hiring, I would go about it this way:</p>\n\n<p>Hand over a print-out of a photoshopped web page representing a clear semantic component tree underneath. Ask the person how he or she would come to a result in html. Just ask him or her to think out loud. What goes through one's head when seeing a page, knowing it needs to be developed. </p>\n\n<p>Then it comes down to the approach the candidate takes.</p>\n\n<p>Choosing the best available markup for each specific html section is one (important) aspect, but can be mastered with experienced people around to guide a new employee. Being able to properly break down a design into its semantic components, identifying sections and separating primary and secondary content from navigation is not math or science and therefore hard to test. But a conversation about the approach of breaking down a page might separate experienced people from beginners.</p>\n\n<p>But as I said in my first line, we usually ask for what kind of web-related work a person has done in his or her free time, such as a blog, game or demo. If done anything, the person usually was really good at front-end development or was eager to learn and adapt.</p>\n"
},
{
"answer_id": 305689,
"author": "Mike B",
"author_id": 3609,
"author_profile": "https://Stackoverflow.com/users/3609",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have any experience with hiring, but I've attended a number of Web Developer interviews and can relate my experiences.</p>\n\n<p>Out of all my interviews one method really stuck out as the best way of discovering true talent. I'll admit that I'm no expert, and this is probably why I didn't get the job, but this was a fantastic way of weeding out those that were capable and those that were great.</p>\n\n<p>We were asked a couple of questions about DOM, Object-Orientation, Closures, XML Namespaces and general Web Design, then we were taken into a quiet office with a nice view across the nearby river and asked to write a few examples to show our ability. We were left alone, but were told that the source code and our browser history would be viewed after, if we needed to use a browser. We were asked to make a company intranet using the following:</p>\n\n<ul>\n<li>A simple three column layout</li>\n<li>A good-looking table using CSS</li>\n<li>A usable but good-looking Navigation Bar.</li>\n<li>Dynamic loading using XML and JavaScript</li>\n</ul>\n\n<p>Given a small amount of time to do this, you get to see people that can really do this stuff. Whilst perhaps their example could always be better or more suited to different applications it just goes to show that the best way to show the skill of a developer is to <strong>get them to make something!</strong> If you know your stuff and they know their stuff their code will be good.</p>\n"
},
{
"answer_id": 14874465,
"author": "Vadim",
"author_id": 2071785,
"author_profile": "https://Stackoverflow.com/users/2071785",
"pm_score": 3,
"selected": false,
"text": "<p>I can suggest you online test, that includes HTML, CSS and JavaScript together.</p>\n\n<p><a href=\"http://tests4geeks.com/test/html-css-javascript\" rel=\"nofollow\">http://tests4geeks.com/test/html-css-javascript</a></p>\n\n<p>It has 60 questions (20 for each subject). And you will recieve the report via email, when the candidate finishes the test.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27083/"
] |
I would like to create a window with a progressbar which shows the current status of Spring's object instantiation. From Spring.Net's [documentation](http://www.springframework.net/docs/1.1.2/reference/html/objects.html#objects-factory-customizing) it seems that `IObjectPostProcessors` is the right point to start and track whenever an Object has been instanciated. However in order to get "Percentage of instantiated classes" I need to ask `ObjectDefinitionCount` of spring's factory to get the number of configured object. However this does not work until the contextcreation has been finished (also [this problem](https://stackoverflow.com/questions/179140/how-do-i-find-out-when-the-springnet-root-context-has-loaded) problem seems to be related).
If it's not possible to use Spring to get the start-up status, how do you display information during application start up to the user?
|
When I interview people for a position of Client-Side developer I try to figure out:
```
1) Understanding DOM (what is that, how is it related to HTML etc)
2) Understanding XML/namespaces
3) Understanding JavaScript (object-oriented? what otherwise)
4) Knowing approaches to componentization (XBL, HTC) - plus
5) Understanding OO principles
6) JavaScript closures
7) Memory leaks in browsers
```
The only simple test case I give right away:
```
<script type="text/javascript">
var a = 1;
</script>
```
I suggest interviewee to explain in technical terms that line.
And I also check on overall awareness of the current state of the Web technologies, among other questions I suggest designing a web-browser where interviewee is suggested to pick technologies he would put into his brand-new creature, suggest ones that might be missing from the current client-side platform.
|
198,343 |
<p>We're working with a fixed transaction log size on our databases, and I'd like to put together an application to monitor the log sizes so we can see when things are getting too tight and we need to grow the fixed trn log. </p>
<p>Is there any TSQL command that I can run which will tell me the current size of the transaction log, and the fixed limit of the transaction log?</p>
|
[
{
"answer_id": 198363,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 4,
"selected": false,
"text": "<p>A quick google search revealed this:</p>\n\n<pre><code>DBCC SQLPERF ( LOGSPACE )\n</code></pre>\n\n<p>Why aren't you using autogrowth on the transaction log? It seems like this would be a more reliable solution.</p>\n"
},
{
"answer_id": 198427,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": false,
"text": "<p>This is off the top of my head, so you might want to double-check the math...</p>\n\n<pre><code>SELECT\n (size * 8)/1024.0 AS size_in_mb,\n CASE\n WHEN max_size = -1 THEN 9999999 -- Unlimited growth, so handle this how you want\n ELSE (max_size * 8)/1024.0\n END AS max_size_in_mb\nFROM\n MyDB.sys.database_files\nWHERE\n data_space_id = 0 -- Log file\n</code></pre>\n\n<p>There is more that you can get from that system view, such as the growth increment, whether or not the log is set to autogrow, and whether it is set to grow by a specific amount or by a percentage.</p>\n\n<p>HTH!</p>\n"
},
{
"answer_id": 839426,
"author": "Diego",
"author_id": 65990,
"author_profile": "https://Stackoverflow.com/users/65990",
"pm_score": 1,
"selected": false,
"text": "<p>If you really need to stick to a fixed size transaction log, I'd suggest to set it to a reasonable size, allowing some margin, and then do one of the following two:</p>\n\n<ul>\n<li>Set database recovery mode to SIMPLE, if you don't need point in time recovery. In simple words, it will allow transaction log to \"self-recycle\" the space.</li>\n</ul>\n\n<p>OR</p>\n\n<ul>\n<li>If you must keep recovery mode to FULL, schedule a job which performs a backup of transaction log. This will free space in the transaction log, and also allow you to do point in time recovery, if needed.</li>\n</ul>\n\n<p>Also, maybe you can find the following article useful: <a href=\"http://support.microsoft.com/kb/873235\" rel=\"nofollow noreferrer\">How to stop the transaction log of a SQL Server database from growing unexpectedly</a>.</p>\n"
},
{
"answer_id": 7085251,
"author": "Myles Yamada",
"author_id": 897547,
"author_profile": "https://Stackoverflow.com/users/897547",
"pm_score": 6,
"selected": true,
"text": "<p>I used your code but, there was an error converting to an int. \n\"Msg 8115, Level 16, State 2, Line 1 Arithmetic overflow error converting expression to data type int.\" So wherever there was an \"*8\" I changed it to *8.0 and the code works perfectly.</p>\n\n<pre><code>SELECT (size * 8.0)/1024.0 AS size_in_mb\n , CASE\n WHEN max_size = -1 \n THEN 9999999 -- Unlimited growth, so handle this how you want\n ELSE (max_size * 8.0)/1024.0 END AS max_size_in_mb\n FROM YOURDBNAMEHERE.sys.database_files\n WHERE data_space_id = 0 \n</code></pre>\n"
},
{
"answer_id": 9309286,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 4,
"selected": false,
"text": "<p>Using sys.database_files only gives you the size of the log file and not the size of the log within it. This is not much use if your file is a fixed size anyway. DBCC SQLPERF ( LOGSPACE ) is a bit old school, but works well if you need to support older versions of SQL Server.</p>\n\n<p>Instead you can use the dm_os_performance_counters table like this:</p>\n\n<pre><code>SELECT\n RTRIM(instance_name) [database], \n cntr_value log_size_kb\nFROM \n sys.dm_os_performance_counters \nWHERE \n object_name = 'SQLServer:Databases'\n AND counter_name = 'Log File(s) Used Size (KB)'\n AND instance_name <> '_Total'\n</code></pre>\n"
},
{
"answer_id": 42283692,
"author": "James",
"author_id": 622140,
"author_profile": "https://Stackoverflow.com/users/622140",
"pm_score": 2,
"selected": false,
"text": "<p>For SQL 2008 and later, <code>FILEPROPERTY</code> also exposes the amount of space used within a file and is much less complicated than all the other answers:</p>\n\n<pre><code>select [Name], physical_name [Path], CAST(size AS BIGINT)*8192 [TotalBytes], CAST(FILEPROPERTY(name,'SpaceUsed') AS BIGINT)*8192 [UsedBytes], (case when max_size<0 then -1 else CAST(max_size AS BIGINT)*8192 end) [MaxBytes]\nfrom sys.database_files\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21973/"
] |
We're working with a fixed transaction log size on our databases, and I'd like to put together an application to monitor the log sizes so we can see when things are getting too tight and we need to grow the fixed trn log.
Is there any TSQL command that I can run which will tell me the current size of the transaction log, and the fixed limit of the transaction log?
|
I used your code but, there was an error converting to an int.
"Msg 8115, Level 16, State 2, Line 1 Arithmetic overflow error converting expression to data type int." So wherever there was an "\*8" I changed it to \*8.0 and the code works perfectly.
```
SELECT (size * 8.0)/1024.0 AS size_in_mb
, CASE
WHEN max_size = -1
THEN 9999999 -- Unlimited growth, so handle this how you want
ELSE (max_size * 8.0)/1024.0 END AS max_size_in_mb
FROM YOURDBNAMEHERE.sys.database_files
WHERE data_space_id = 0
```
|
198,346 |
<p>I've found a few samples online but I'd like to get feedback from people who use PHP daily as to potential security or performance considerations and their solutions.</p>
<p>Note that I am only interested in uploading a single file at a time.</p>
<p>Ideally no browser plugin would be required (Flash/Java), although it would be interesting to know the benefits of using a plugin.</p>
<p>I would like to know both the best HTML form code and PHP processing code.</p>
|
[
{
"answer_id": 198361,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<p>The main benefit of Flash is it allows you to upload multiple files. The main benefit of Java is it allows drag-and-drop from the file system. Sorry for not answering the central question, but I thought I'd throw that in as it's fairly simple.</p>\n"
},
{
"answer_id": 198384,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "<p>Have a read of <a href=\"http://docs.php.net/manual/en/features.file-upload.php\" rel=\"noreferrer\">this introduction</a> which should tell you everything you need to know. The user comments are fairly useful as well.</p>\n"
},
{
"answer_id": 198459,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 6,
"selected": true,
"text": "<h1>File Upload Tutorial</h1>\n\n<h2>HTML</h2>\n\n<pre><code><form enctype=\"multipart/form-data\" action=\"action.php\" method=\"POST\">\n <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"1000000\" />\n <input name=\"userfile\" type=\"file\" />\n <input type=\"submit\" value=\"Go\" />\n</form>\n</code></pre>\n\n<ul>\n<li><code>action.php</code> is the name of a PHP file that will process the upload (shown below)</li>\n<li><code>MAX_FILE_SIZE</code> must appear immediately before the input with type <code>file</code>. This value can easily be manipulated on the client so should not be relied upon. Its main benefit is to provide the user with early warning that their file is too large, before they've uploaded it.</li>\n<li>You can change the name of the input with type <code>file</code>, but make sure it doesn't contain any spaces. You must also update the corresponding value in the PHP file (below).</li>\n</ul>\n\n<h2>PHP</h2>\n\n<pre><code><?php\n$uploaddir = \"/www/uploads/\";\n$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);\n\necho '<pre>';\nif (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {\n echo \"Success.\\n\";\n} else {\n echo \"Failure.\\n\";\n}\n\necho 'Here is some more debugging info:';\nprint_r($_FILES);\nprint \"</pre>\";\n?>\n</code></pre>\n\n<p>The upload-to folder should not be located in a place that's accessible via HTTP, otherwise it would be possible to upload a PHP script and execute it upon the server.</p>\n\n<p>Printing the value of <code>$_FILES</code> can give a hint as to what's going on. For example:</p>\n\n<pre>\n Array\n (\n [userfile] => Array\n (\n [name] => Filename.ext\n [type] => \n [tmp_name] => \n [error] => 2\n [size] => 0\n )\n )\n</pre>\n\n<p>This structure gives some information as to the file's name, MIME type, size and error code.</p>\n\n<h2>Error Codes</h2>\n\n<blockquote>\n <p>0 Indicates that there was no errors and file has been uploaded successfully<br>\n 1 Indicates that the file exceeds the maximum file size defined in php.ini. If you would like to change the maximum file size, you need to open your php.ini file, identify the line which reads: upload_max_filesize = 2M and change the value from 2M (2MB) to whatever you need<br>\n 2 Indicates that the maximum file size defined manually, within an on page script has been exceeded<br>\n 3 Indicates that file has only been uploaded partially<br>\n 4 Indicates that the file hasn't been specified (empty file field)<br>\n 5 Not defined yet<br>\n 6 Indicates that there´s no temporary folder<br>\n 7 Indicates that the file cannot be written to the disk </p>\n</blockquote>\n\n<h2><code>php.ini</code> Configuration</h2>\n\n<p>When running this setup with larger files you may receive errors. Check your <code>php.ini</code> file for these keys:</p>\n\n<p><code>max_execution_time = 30</code><br>\n<code>upload_max_filesize = 2M</code></p>\n\n<p>Increasing these values as appropriate may help. When using Apache, changes to this file require a restart.</p>\n\n<p>The maximum memory permitted value (set via <code>memory_limit</code>) does not play a role here as the file is written to the tmp directory as it is uploaded. The location of the tmp directory is optionally controlled via <code>upload_tmp_dir</code>.</p>\n\n<h2>Checking file mimetypes</h2>\n\n<p>You should check the filetype of what the user is uploading - the best practice is to validate against a list of allowed filetypes. A potential risk of allowing any file is that <strong>a user could potentially upload PHP code to the server and then run it</strong>.</p>\n\n<p>You can use the very useful <a href=\"http://www.php.net/manual/en/ref.fileinfo.php\" rel=\"noreferrer\"><code>fileinfo</code></a> extension (that supersedes the older <a href=\"http://www.php.net/manual/en/function.mime-content-type.php\" rel=\"noreferrer\"><code>mime_content_type</code></a> function) to validate mime-types.</p>\n\n<pre><code>// FILEINFO_MIME set to return MIME types, will return string of info otherwise\n$fileinfo = new finfo(FILEINFO_MIME);\n$file = $fileinfo->file($_FILE['filename']);\n\n$allowed_types = array('image/jpeg', 'image/png');\nif(!in_array($file, $allowed_types))\n{\n die('Files of type' . $file . ' are not allowed to be uploaded.');\n}\n// Continue\n</code></pre>\n\n<h2>More Information</h2>\n\n<p>You can read more on handling file uploads at the <a href=\"http://docs.php.net/manual/en/features.file-upload.php\" rel=\"noreferrer\">PHP.net manual</a>.</p>\n\n<h2>For PHP 5.3+</h2>\n\n<pre><code>//For those who are using PHP 5.3, the code varies.\n$fileinfo = new finfo(FILEINFO_MIME_TYPE);\n$file = $fileinfo->file($_FILE['filename']['tmp_name']);\n$allowed_types = array('image/jpeg', 'image/png');\nif(!in_array($file, $allowed_types))\n{\n die('Files of type' . $file . ' are not allowed to be uploaded.');\n}\n// Continue\n</code></pre>\n\n<h2>More Information</h2>\n\n<p>You can read more on FILEINFO_MIME_TYPE at the <a href=\"http://php.net/manual/en/fileinfo.constants.php\" rel=\"noreferrer\">PHP.net documentation</a>.</p>\n"
},
{
"answer_id": 199899,
"author": "cole",
"author_id": 910,
"author_profile": "https://Stackoverflow.com/users/910",
"pm_score": 2,
"selected": false,
"text": "<p>Security is a pretty big thing with regards to file uploads, adding a .htaccess to the uploads folder which stops scripts being run from it could be handy to add just an extra layer of security.</p>\n\n<p>.htaccess</p>\n\n<pre><code>Options -Indexes\nOptions -ExecCGI\nAddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi \n</code></pre>\n\n<p>Reference: <a href=\"http://www.mysql-apache-php.com/fileupload-security.htm\" rel=\"nofollow noreferrer\">http://www.mysql-apache-php.com/fileupload-security.htm</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24874/"
] |
I've found a few samples online but I'd like to get feedback from people who use PHP daily as to potential security or performance considerations and their solutions.
Note that I am only interested in uploading a single file at a time.
Ideally no browser plugin would be required (Flash/Java), although it would be interesting to know the benefits of using a plugin.
I would like to know both the best HTML form code and PHP processing code.
|
File Upload Tutorial
====================
HTML
----
```
<form enctype="multipart/form-data" action="action.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input name="userfile" type="file" />
<input type="submit" value="Go" />
</form>
```
* `action.php` is the name of a PHP file that will process the upload (shown below)
* `MAX_FILE_SIZE` must appear immediately before the input with type `file`. This value can easily be manipulated on the client so should not be relied upon. Its main benefit is to provide the user with early warning that their file is too large, before they've uploaded it.
* You can change the name of the input with type `file`, but make sure it doesn't contain any spaces. You must also update the corresponding value in the PHP file (below).
PHP
---
```
<?php
$uploaddir = "/www/uploads/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "Success.\n";
} else {
echo "Failure.\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
```
The upload-to folder should not be located in a place that's accessible via HTTP, otherwise it would be possible to upload a PHP script and execute it upon the server.
Printing the value of `$_FILES` can give a hint as to what's going on. For example:
```
Array
(
[userfile] => Array
(
[name] => Filename.ext
[type] =>
[tmp_name] =>
[error] => 2
[size] => 0
)
)
```
This structure gives some information as to the file's name, MIME type, size and error code.
Error Codes
-----------
>
> 0 Indicates that there was no errors and file has been uploaded successfully
>
> 1 Indicates that the file exceeds the maximum file size defined in php.ini. If you would like to change the maximum file size, you need to open your php.ini file, identify the line which reads: upload\_max\_filesize = 2M and change the value from 2M (2MB) to whatever you need
>
> 2 Indicates that the maximum file size defined manually, within an on page script has been exceeded
>
> 3 Indicates that file has only been uploaded partially
>
> 4 Indicates that the file hasn't been specified (empty file field)
>
> 5 Not defined yet
>
> 6 Indicates that there´s no temporary folder
>
> 7 Indicates that the file cannot be written to the disk
>
>
>
`php.ini` Configuration
-----------------------
When running this setup with larger files you may receive errors. Check your `php.ini` file for these keys:
`max_execution_time = 30`
`upload_max_filesize = 2M`
Increasing these values as appropriate may help. When using Apache, changes to this file require a restart.
The maximum memory permitted value (set via `memory_limit`) does not play a role here as the file is written to the tmp directory as it is uploaded. The location of the tmp directory is optionally controlled via `upload_tmp_dir`.
Checking file mimetypes
-----------------------
You should check the filetype of what the user is uploading - the best practice is to validate against a list of allowed filetypes. A potential risk of allowing any file is that **a user could potentially upload PHP code to the server and then run it**.
You can use the very useful [`fileinfo`](http://www.php.net/manual/en/ref.fileinfo.php) extension (that supersedes the older [`mime_content_type`](http://www.php.net/manual/en/function.mime-content-type.php) function) to validate mime-types.
```
// FILEINFO_MIME set to return MIME types, will return string of info otherwise
$fileinfo = new finfo(FILEINFO_MIME);
$file = $fileinfo->file($_FILE['filename']);
$allowed_types = array('image/jpeg', 'image/png');
if(!in_array($file, $allowed_types))
{
die('Files of type' . $file . ' are not allowed to be uploaded.');
}
// Continue
```
More Information
----------------
You can read more on handling file uploads at the [PHP.net manual](http://docs.php.net/manual/en/features.file-upload.php).
For PHP 5.3+
------------
```
//For those who are using PHP 5.3, the code varies.
$fileinfo = new finfo(FILEINFO_MIME_TYPE);
$file = $fileinfo->file($_FILE['filename']['tmp_name']);
$allowed_types = array('image/jpeg', 'image/png');
if(!in_array($file, $allowed_types))
{
die('Files of type' . $file . ' are not allowed to be uploaded.');
}
// Continue
```
More Information
----------------
You can read more on FILEINFO\_MIME\_TYPE at the [PHP.net documentation](http://php.net/manual/en/fileinfo.constants.php).
|
198,357 |
<p>A lot of programming languages and frameworks do/allow/require something that I can't seem to find the name for, even though there probably is one in computer science. What they basically do is bind to a variable/object/class/function by name. </p>
<p><a href="http://www.adobe.com/products/flex/" rel="noreferrer">Flex</a> example ("selectAll()"):</p>
<pre><code><mx:Button click="selectAll()" label="Select All"/>
</code></pre>
<p><a href="http://mate.asfusion.com/" rel="noreferrer">Mate</a> example ("price"):</p>
<pre><code><Injectors target="{QuotePanel}">
<PropertyInjector targetKey="price" source="{QuoteManager}" sourceKey="currentPrice" />
</Injectors>
</code></pre>
<p>Java example ("Foo"):</p>
<pre><code>Class.forName("Foo")
</code></pre>
<p>There are many other examples. You get the idea. What troubles me is that there is virtually no way to verify this at compile-time, and not much the IDE can do to help in terms of code completion, navigation, and refactoring. But that's besides the point.</p>
<p>My question is, what is this called? <strong><em>I don't think it's one of these: <a href="http://en.wikipedia.org/wiki/Dynamic_binding" rel="noreferrer">dynamic binding</a>, <a href="http://en.wikipedia.org/wiki/Name_binding" rel="noreferrer">name binding</a>, <a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)" rel="noreferrer">reflection</a></em></strong></p>
<p><strong>Update</strong>: No, this is not a quiz, sorry if it sounds like one. It's simply a matter of "name that song" for programming.</p>
<p><strong>Update</strong>: Answers that helped:</p>
<ul>
<li>From Tim Lesher: It's called "late binding", "dynamic binding", or "runtime binding". <em>The fact that it binds by a string is just an implementation detail</em>...</li>
<li>From Konrad Rudolph: ...<em>it's simply input for an interpreter</em>.</li>
</ul>
<p><strong>Update</strong>: As people have correctly pointed out, some of the examples are late binding, some are reflection, some are runtime-evaluation (interpretation), etc. However, I conclude there probably is no name that describes them all. It's just a bunch of examples that do have something in common, but not enough to give it a name. I liked the "everything is a string" answer, but even though it's funny, it doesn't fully do it justice either.</p>
|
[
{
"answer_id": 198364,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>What makes you think that <code>Class.forName</code> isn't reflection?</p>\n"
},
{
"answer_id": 198368,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 2,
"selected": false,
"text": "<p>Late binding?</p>\n"
},
{
"answer_id": 198370,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 3,
"selected": false,
"text": "<p>Late binding</p>\n"
},
{
"answer_id": 198371,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 2,
"selected": false,
"text": "<p>Reflection</p>\n"
},
{
"answer_id": 198374,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>In the .NET world we call this databinding, and it has handled using reflection.</p>\n\n<p>It also reminds me strongly of dependency injection.</p>\n"
},
{
"answer_id": 198379,
"author": "Alan",
"author_id": 5878,
"author_profile": "https://Stackoverflow.com/users/5878",
"pm_score": 0,
"selected": false,
"text": "<p>Smells like a function pointer to me.</p>\n"
},
{
"answer_id": 198388,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "<p>The Java example you gave is called Dynamic Class Loading. I'm not sure if the other examples are the same thing. But this is useful in reflection. Maybe you are looking for the design pattern called Inversion of control.</p>\n"
},
{
"answer_id": 198393,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 1,
"selected": false,
"text": "<p>\"introspection\" ?</p>\n"
},
{
"answer_id": 198408,
"author": "TheVillageIdiot",
"author_id": 13198,
"author_profile": "https://Stackoverflow.com/users/13198",
"pm_score": 2,
"selected": false,
"text": "<p>The flex thing can be termed as late binding, if it works like normal html. Until user clicks the button the runtime does not bother to find if the function exists or not.\nThe second thing is dependency injection, which involves function pointers (by way of Interfaces) and reflection.\nThe java one is definitely reflection.</p>\n\n<p>I think may be you were not able to word your question properly or had chosen bad examples to illustrate your thought.</p>\n"
},
{
"answer_id": 198436,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>By the way, I surmise that the Flex code you showed us uses simply ActionScript invocation, in which case the <code>click</code> attribute would simply be <code>eval</code>'d by the interpreter of the Flex document. Thus, there's no special magic behind this kind of code, it's simply input for an interpreter.</p>\n"
},
{
"answer_id": 198437,
"author": "Tim Lesher",
"author_id": 14942,
"author_profile": "https://Stackoverflow.com/users/14942",
"pm_score": 5,
"selected": true,
"text": "<p>It's called \"late binding\", \"dynamic binding\", or \"runtime binding\". The fact that it binds by a string is just an implementation detail, although it does imply that the string-to-symbol mapping exists at runtime (which some languages, like c++, don't provide).</p>\n\n<p>\"Introspection\" or \"reflection\", on the other hand, refer to the ability to find out what interfaces, methods, or attributes an object implements at runtime.</p>\n\n<p>It's true that dynamically-bound symbols can't be verified before execution; that's what makes them different from statically-bound symbols. </p>\n"
},
{
"answer_id": 198440,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 0,
"selected": false,
"text": "<p>The first example is an example of how a namespaced xml can assume meanings on compiling time,\nThe second is both a databinding/dependancy injection\nThe third example is Reflection, if I had to tag all this 3 examples with a name I think I will go for \"Syntax\"</p>\n"
},
{
"answer_id": 198441,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 1,
"selected": false,
"text": "<p>I think the Flex example isn't quite the same as the one in Java (don't know the other stuff). The Java example is clearly something I would call <strong>late binding</strong>, because the class-loader resolves the classname at runtime, the latest possible time to do that.</p>\n\n<p>The Flex MXML is mainly another syntax, which eventually gets compiled to something you could have also written in ActionScript. As far as I can tell, the mx:Button and the selectAll() function are <em>resolved at compile time</em>. At least mxmlc gives errors if you use a undefined symbol there.</p>\n"
},
{
"answer_id": 198514,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>There is a scenario where the compiler can help this... Code Generation.</p>\n"
},
{
"answer_id": 198619,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 1,
"selected": false,
"text": "<p>If the type of variable is not known until runtime, then it's late binding. If the variable type is known at compile time, then it's early binding. </p>\n\n<p>Intellisense, code completion and all the other IDE features you talk about are only available on early bound variables.</p>\n"
},
{
"answer_id": 198933,
"author": "ja.",
"author_id": 15467,
"author_profile": "https://Stackoverflow.com/users/15467",
"pm_score": 1,
"selected": false,
"text": "<p>I'd call it \"Everything is a String\", \"String as Universal Data Type\", or \"String Abuse\".</p>\n\n<p>Support:</p>\n\n<p><a href=\"http://research.microsoft.com/~emeijer/papers/xml2003/xml2003.html\" rel=\"nofollow noreferrer\">http://research.microsoft.com/~emeijer/papers/xml2003/xml2003.html</a></p>\n\n<p><a href=\"http://blog.moertel.com/articles/2006/10/18/a-type-based-solution-to-the-strings-problem\" rel=\"nofollow noreferrer\"> http://blog.moertel.com/articles/2006/10/18/a-type-based-solution-to-the-strings-problem\n</a></p>\n\n<p><a href=\"http://pveentjer.wordpress.com/2006/10/11/string-is-not-a-good-universal-datatype/\" rel=\"nofollow noreferrer\"> http://pveentjer.wordpress.com/2006/10/11/string-is-not-a-good-universal-datatype/\n</a></p>\n\n<p><a href=\"http://computer-programming-languages.suite101.com/article.cfm/abused_strings_considered_harmful\" rel=\"nofollow noreferrer\"> http://computer-programming-languages.suite101.com/article.cfm/abused_strings_considered_harmful\n</a></p>\n"
},
{
"answer_id": 216438,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 2,
"selected": false,
"text": "<p>The second and third examples are examples of reflection or late binding, but the first example isn't.</p>\n\n<pre><code><mx:Button click=\"selectAll()\" label=\"Select All\"/>\n</code></pre>\n\n<p>Is rewritten as ActionScript before compilation, with the <code>selectAll()</code> part being tucked inside an event handler function. Something like this (how it is done exactly can be checked by adding <code>-keep-generated-actionscript</code> to the compiler flags):</p>\n\n<pre><code>_button1 = new Button();\n_button1.label = \"Select All\";\n_button1.addEventListener(\"click\", function( event : Event ) : void {\n selectAll();\n});\n</code></pre>\n\n<p>The compiler determines if the attributes are events, styles or properties, but since this is done at compile time it is not reflection. Reflection, by definition, is done at runtime.</p>\n\n<p>I think it could be argued that the second and third examples are reflection, but also that they are examples of late binding. None of them actually determines the capabilities of the objects they work on, so in that way they are not reflection. However, I would say that the term \"reflection\" is very often used in a broad sense to mean anything that calls methods whose names are determined at runtime, or creates objects from classes named only at runtime. If you want to be precise \"late binding\" is probably the most correct answer, but I think \"reflection\" is good enough.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13041/"
] |
A lot of programming languages and frameworks do/allow/require something that I can't seem to find the name for, even though there probably is one in computer science. What they basically do is bind to a variable/object/class/function by name.
[Flex](http://www.adobe.com/products/flex/) example ("selectAll()"):
```
<mx:Button click="selectAll()" label="Select All"/>
```
[Mate](http://mate.asfusion.com/) example ("price"):
```
<Injectors target="{QuotePanel}">
<PropertyInjector targetKey="price" source="{QuoteManager}" sourceKey="currentPrice" />
</Injectors>
```
Java example ("Foo"):
```
Class.forName("Foo")
```
There are many other examples. You get the idea. What troubles me is that there is virtually no way to verify this at compile-time, and not much the IDE can do to help in terms of code completion, navigation, and refactoring. But that's besides the point.
My question is, what is this called? ***I don't think it's one of these: [dynamic binding](http://en.wikipedia.org/wiki/Dynamic_binding), [name binding](http://en.wikipedia.org/wiki/Name_binding), [reflection](http://en.wikipedia.org/wiki/Reflection_(computer_science))***
**Update**: No, this is not a quiz, sorry if it sounds like one. It's simply a matter of "name that song" for programming.
**Update**: Answers that helped:
* From Tim Lesher: It's called "late binding", "dynamic binding", or "runtime binding". *The fact that it binds by a string is just an implementation detail*...
* From Konrad Rudolph: ...*it's simply input for an interpreter*.
**Update**: As people have correctly pointed out, some of the examples are late binding, some are reflection, some are runtime-evaluation (interpretation), etc. However, I conclude there probably is no name that describes them all. It's just a bunch of examples that do have something in common, but not enough to give it a name. I liked the "everything is a string" answer, but even though it's funny, it doesn't fully do it justice either.
|
It's called "late binding", "dynamic binding", or "runtime binding". The fact that it binds by a string is just an implementation detail, although it does imply that the string-to-symbol mapping exists at runtime (which some languages, like c++, don't provide).
"Introspection" or "reflection", on the other hand, refer to the ability to find out what interfaces, methods, or attributes an object implements at runtime.
It's true that dynamically-bound symbols can't be verified before execution; that's what makes them different from statically-bound symbols.
|
198,360 |
<p>I would like to host a silverlight control in winforms via a winforms browser, but for it to work I need some way for the forms to talk to the silverlight, and also the other way around. Would it be possible to somehow have the two interact with each other using JavaScript as a middleman? I.e., have the form speak to the browser's javascript, and have that speak to the silverlight control? Is there a better way? Or even a way at all? (other than compiling the code as silverlight and wpf)</p>
|
[
{
"answer_id": 198378,
"author": "smaclell",
"author_id": 22914,
"author_profile": "https://Stackoverflow.com/users/22914",
"pm_score": 0,
"selected": false,
"text": "<p>Silverlight in a winform app just sounds like bad news. It would mean you are running to different CLR's in a single app and would have to deal with alot of added complexity to make it work. If possible consider using the full WPF within your app instead here is a <a href=\"http://blog.paranoidferret.com/index.php/2008/06/24/wpf-tutorial-using-wpf-in-winforms/\" rel=\"nofollow noreferrer\">link</a> showing you how.</p>\n"
},
{
"answer_id": 200179,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look at <a href=\"http://www.blendables.com/labs/Desklighter/Default.aspx\" rel=\"nofollow noreferrer\">Desklighter</a>. Not exactly what you are looking for but it does proof that it should be possible?</p>\n"
},
{
"answer_id": 208920,
"author": "wahrhaft",
"author_id": 17986,
"author_profile": "https://Stackoverflow.com/users/17986",
"pm_score": 5,
"selected": true,
"text": "<p>I think using the Windows Forms WebBrowser control is your best bet. To do this, you'll need your Silverlight app on a webpage, then you point your WebBrowser at the page's URI.</p>\n\n<p>To keep your WebBrowser control from acting like IE, I'd recommend setting the following:</p>\n\n<pre><code>webBrowser.AllowNavigation = false;\nwebBrowser.AllowWebBrowserDrop = false;\nwebBrowser.IsWebBrowserContextMenuEnabled = false;\nwebBrowser.WebBrowserShortcutsEnabled = false;\n</code></pre>\n\n<p>Calling methods on your form from within Silverlight is easy enough to do. To start, you need a class that has all the methods you want to call from Silverlight. You can use your form itself or another object, but you need to mark the class with the [ComVisible(true)] attribute. Then you assign your object to the WebBrowser.ObjectForScripting property. This exposes your object as \"window.external\" on the webpage.</p>\n\n<pre><code>[ComVisible(true)]\npublic partial class Form1 : Form\n{\n ......\n webBrowser.ObjectForScripting = this;\n ......\n public void CallMeInForm(string something)\n {\n MessageBox.Show(\"Silverlight said: \" + something);\n }\n}\n</code></pre>\n\n<p>That's it for inside your Windows Forms project. Inside of your Silverlight app, you need to pick up this ObjectForScripting and invoke methods on it. To call the method in my example above, use the following lines:</p>\n\n<pre><code>using System.Windows.Browser;\n......\nScriptObject myForm = (ScriptObject)HtmlPage.Window.GetProperty(\"external\");\nmyForm.Invoke(\"CallMeInForm\", \"testing 1 2 3\");\n</code></pre>\n\n<p>The Invoke command lets you pass any number and type of parameters to your function, although I suspect it wouldn't like it very much if you try passing complex datatypes around. But if you needed to do so, you could always use serialization.</p>\n\n<p>Calling Silverlight functions from your form seems to be the tricker direction. I haven't figured this one out completely yet.</p>\n\n<p>In your Silverlight app, you also expose functions to the webpage. To do this, use the HtmlPage.RegisterScriptableObject() function. Again, you can pass in any class with methods you want to expose. For a method to be exposed, though, you have to mark it with the [ScriptableMember] attribute.</p>\n\n<pre><code>HtmlPage.RegisterScriptableObject(\"Page\", this);\n......\n[ScriptableMember]\npublic void CallMeInSilverlight(string message)\n{\n HtmlPage.Window.Alert(\"The form said: \" + message);\n}\n</code></pre>\n\n<p>At this point, your method is exposed to JavaScript on the page and you could call it like so, assuming you added <code>id=\"silverlightControl\"</code> to your <code><object></code> element:</p>\n\n<pre><code>document.getElementById('silverlightControl').Content.Page.CallMeInSilverlight(\"testing 1 2 3\");\n</code></pre>\n\n<p>Notice the <code>Page</code> property? That's what the call to <code>RegisterScriptableObject()</code> gave us. Now, let's wrap this into a tidy JavaScript method:</p>\n\n<pre><code><script type=\"text/javascript\">\n function CallMe(message) {\n var control = document.getElementById('silverlightControl');\n control.Content.Page.CallMeInSilverlight(message);\n }\n</script>\n</code></pre>\n\n<p>And now we can call the <code>CallMe()</code> method from the Windows Forms app like so:</p>\n\n<pre><code>public void CallToSilverlight()\n{\n webBrowser.InvokeScript(\"CallMe\", new object[] { \"testing 1 2 3\" });\n}\n</code></pre>\n"
},
{
"answer_id": 2609814,
"author": "Charles",
"author_id": 48483,
"author_profile": "https://Stackoverflow.com/users/48483",
"pm_score": 1,
"selected": false,
"text": "<p>If all you <em>really</em> need to do is host Silverlight in a desktop app, I'd suggest you check out <a href=\"http://jmorrill.hjtcentral.com/\" rel=\"nofollow noreferrer\">Jeremiah Morrill</a>'s <a href=\"http://silverlightviewport.codeplex.com/\" rel=\"nofollow noreferrer\">SilverlightViewport</a> project. It allows you to embed a Silverlight application in a WPF or XNA app. It's still very alpha, but you might find it useful.</p>\n\n<p>Here's a picture to wet your appetite:</p>\n\n<p><a href=\"http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=silverlightviewport&DownloadId=97946\" rel=\"nofollow noreferrer\">http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=silverlightviewport&DownloadId=97946</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
I would like to host a silverlight control in winforms via a winforms browser, but for it to work I need some way for the forms to talk to the silverlight, and also the other way around. Would it be possible to somehow have the two interact with each other using JavaScript as a middleman? I.e., have the form speak to the browser's javascript, and have that speak to the silverlight control? Is there a better way? Or even a way at all? (other than compiling the code as silverlight and wpf)
|
I think using the Windows Forms WebBrowser control is your best bet. To do this, you'll need your Silverlight app on a webpage, then you point your WebBrowser at the page's URI.
To keep your WebBrowser control from acting like IE, I'd recommend setting the following:
```
webBrowser.AllowNavigation = false;
webBrowser.AllowWebBrowserDrop = false;
webBrowser.IsWebBrowserContextMenuEnabled = false;
webBrowser.WebBrowserShortcutsEnabled = false;
```
Calling methods on your form from within Silverlight is easy enough to do. To start, you need a class that has all the methods you want to call from Silverlight. You can use your form itself or another object, but you need to mark the class with the [ComVisible(true)] attribute. Then you assign your object to the WebBrowser.ObjectForScripting property. This exposes your object as "window.external" on the webpage.
```
[ComVisible(true)]
public partial class Form1 : Form
{
......
webBrowser.ObjectForScripting = this;
......
public void CallMeInForm(string something)
{
MessageBox.Show("Silverlight said: " + something);
}
}
```
That's it for inside your Windows Forms project. Inside of your Silverlight app, you need to pick up this ObjectForScripting and invoke methods on it. To call the method in my example above, use the following lines:
```
using System.Windows.Browser;
......
ScriptObject myForm = (ScriptObject)HtmlPage.Window.GetProperty("external");
myForm.Invoke("CallMeInForm", "testing 1 2 3");
```
The Invoke command lets you pass any number and type of parameters to your function, although I suspect it wouldn't like it very much if you try passing complex datatypes around. But if you needed to do so, you could always use serialization.
Calling Silverlight functions from your form seems to be the tricker direction. I haven't figured this one out completely yet.
In your Silverlight app, you also expose functions to the webpage. To do this, use the HtmlPage.RegisterScriptableObject() function. Again, you can pass in any class with methods you want to expose. For a method to be exposed, though, you have to mark it with the [ScriptableMember] attribute.
```
HtmlPage.RegisterScriptableObject("Page", this);
......
[ScriptableMember]
public void CallMeInSilverlight(string message)
{
HtmlPage.Window.Alert("The form said: " + message);
}
```
At this point, your method is exposed to JavaScript on the page and you could call it like so, assuming you added `id="silverlightControl"` to your `<object>` element:
```
document.getElementById('silverlightControl').Content.Page.CallMeInSilverlight("testing 1 2 3");
```
Notice the `Page` property? That's what the call to `RegisterScriptableObject()` gave us. Now, let's wrap this into a tidy JavaScript method:
```
<script type="text/javascript">
function CallMe(message) {
var control = document.getElementById('silverlightControl');
control.Content.Page.CallMeInSilverlight(message);
}
</script>
```
And now we can call the `CallMe()` method from the Windows Forms app like so:
```
public void CallToSilverlight()
{
webBrowser.InvokeScript("CallMe", new object[] { "testing 1 2 3" });
}
```
|
198,365 |
<p>in Config.groovy I see this:</p>
<pre><code>// set per-environment serverURL stem for creating absolute links
environments {
production {
grails.serverURL = "http://www.changeme.com"
}
}
</code></pre>
<p>what is the correct way to access that at runtime?</p>
|
[
{
"answer_id": 198466,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 4,
"selected": false,
"text": "<p>here it is:</p>\n\n<pre><code>import org.codehaus.groovy.grails.commons.ConfigurationHolder\nprintln ConfigurationHolder.config.grails.serverURL\n</code></pre>\n\n<p>alternatively, in controllers and tags, apparently this will work: </p>\n\n<pre><code>grailsApplication.config.grails.serverURL\n</code></pre>\n\n<p>I needed it in BootStrap, so option 1 was what I needed.</p>\n"
},
{
"answer_id": 198541,
"author": "Robert Fischer",
"author_id": 27561,
"author_profile": "https://Stackoverflow.com/users/27561",
"pm_score": 5,
"selected": false,
"text": "<p>danb is on the right track. However, life gets a bit easier on your fingers if you do a nicer import:</p>\n\n<pre><code>import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH\nprintln CH.config.grails.serverURL\n</code></pre>\n"
},
{
"answer_id": 10597881,
"author": "khylo",
"author_id": 249672,
"author_profile": "https://Stackoverflow.com/users/249672",
"pm_score": 7,
"selected": true,
"text": "<p>In more recent versions of grails ConfigurationHolder has been deprecated.</p>\n\n<p>Instead you should use the grailsApplication object.</p>\n\n<pre><code>grailsApplication.config.grails.serverURL\n</code></pre>\n\n<p>If in a Controller or Service then use dependency injection of grailsApplication object.\ne.g.</p>\n\n<pre><code>class MyController{\n def grailsApplication\n def myAction() {\n grailsApplication.config.grails.serverURL\n }\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/7133580/how-to-access-grails-configuration-in-grails-2-0\">How to access Grails configuration in Grails 2.0?</a> </p>\n"
},
{
"answer_id": 24789570,
"author": "jstricker",
"author_id": 1475872,
"author_profile": "https://Stackoverflow.com/users/1475872",
"pm_score": 3,
"selected": false,
"text": "<p>As mentioned in a few of the comments, another option is the <a href=\"http://grails.org/doc/latest/api/grails/util/Holders.html\"><code>grails.utils.Holders</code></a> class which was added in Grails 2.0. I prefer this approach since you can use it in classes that aren't configured with dependency injection.</p>\n\n<pre><code>import grails.util.Holders\n\nclass Foo {\n def bar() {\n println(Holders.config.grails.serverURL)\n }\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031/"
] |
in Config.groovy I see this:
```
// set per-environment serverURL stem for creating absolute links
environments {
production {
grails.serverURL = "http://www.changeme.com"
}
}
```
what is the correct way to access that at runtime?
|
In more recent versions of grails ConfigurationHolder has been deprecated.
Instead you should use the grailsApplication object.
```
grailsApplication.config.grails.serverURL
```
If in a Controller or Service then use dependency injection of grailsApplication object.
e.g.
```
class MyController{
def grailsApplication
def myAction() {
grailsApplication.config.grails.serverURL
}
```
See [How to access Grails configuration in Grails 2.0?](https://stackoverflow.com/questions/7133580/how-to-access-grails-configuration-in-grails-2-0)
|
198,409 |
<p>Is there code in VBA I can wrap a function with that will let me know the time it took to run, so that I can compare the different running times of functions?</p>
|
[
{
"answer_id": 198702,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 7,
"selected": true,
"text": "<p>Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is <code>QueryPerformanceCounter</code>. Google it for more info. Try pushing the following into a class, call it <code>CTimer</code> say, then you can make an instance somewhere global and just call <code>.StartCounter</code> and <code>.TimeElapsed</code></p>\n\n<pre><code>Option Explicit\n\nPrivate Type LARGE_INTEGER\n lowpart As Long\n highpart As Long\nEnd Type\n\nPrivate Declare Function QueryPerformanceCounter Lib \"kernel32\" (lpPerformanceCount As LARGE_INTEGER) As Long\nPrivate Declare Function QueryPerformanceFrequency Lib \"kernel32\" (lpFrequency As LARGE_INTEGER) As Long\n\nPrivate m_CounterStart As LARGE_INTEGER\nPrivate m_CounterEnd As LARGE_INTEGER\nPrivate m_crFrequency As Double\n\nPrivate Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#\n\nPrivate Function LI2Double(LI As LARGE_INTEGER) As Double\nDim Low As Double\n Low = LI.lowpart\n If Low < 0 Then\n Low = Low + TWO_32\n End If\n LI2Double = LI.highpart * TWO_32 + Low\nEnd Function\n\nPrivate Sub Class_Initialize()\nDim PerfFrequency As LARGE_INTEGER\n QueryPerformanceFrequency PerfFrequency\n m_crFrequency = LI2Double(PerfFrequency)\nEnd Sub\n\nPublic Sub StartCounter()\n QueryPerformanceCounter m_CounterStart\nEnd Sub\n\nProperty Get TimeElapsed() As Double\nDim crStart As Double\nDim crStop As Double\n QueryPerformanceCounter m_CounterEnd\n crStart = LI2Double(m_CounterStart)\n crStop = LI2Double(m_CounterEnd)\n TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency\nEnd Property\n</code></pre>\n"
},
{
"answer_id": 198718,
"author": "Tom Juergens",
"author_id": 2899,
"author_profile": "https://Stackoverflow.com/users/2899",
"pm_score": 2,
"selected": false,
"text": "<p>We've used a solution based on timeGetTime in winmm.dll for millisecond accuracy for many years. See <a href=\"http://www.aboutvb.de/kom/artikel/komstopwatch.htm\" rel=\"nofollow noreferrer\">http://www.aboutvb.de/kom/artikel/komstopwatch.htm</a></p>\n\n<p>The article is in German, but the code in the download (a VBA class wrapping the dll function call) is simple enough to use and understand without being able to read the article.</p>\n"
},
{
"answer_id": 199480,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 6,
"selected": false,
"text": "<p>The Timer function in VBA gives you the number of seconds elapsed since midnight, to 1/100 of a second.</p>\n\n<pre><code>Dim t as single\nt = Timer\n'code\nMsgBox Timer - t\n</code></pre>\n"
},
{
"answer_id": 6820028,
"author": "Kodak",
"author_id": 197559,
"author_profile": "https://Stackoverflow.com/users/197559",
"pm_score": 5,
"selected": false,
"text": "<p>If you are trying to return the time like a stopwatch you could use the\nfollowing API which returns the time in milliseconds since system startup:</p>\n\n<pre><code>Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\nSub testTimer()\nDim t As Long\nt = GetTickCount\n\nFor i = 1 To 1000000\na = a + 1\nNext\n\nMsgBox GetTickCount - t, , \"Milliseconds\"\nEnd Sub\n</code></pre>\n\n<p>after <a href=\"http://www.pcreview.co.uk/forums/grab-time-milliseconds-included-vba-t994765.html\" rel=\"noreferrer\">http://www.pcreview.co.uk/forums/grab-time-milliseconds-included-vba-t994765.html</a> (as timeGetTime in winmm.dll was not working for me and QueryPerformanceCounter was too complicated for the task needed)</p>\n"
},
{
"answer_id": 22563199,
"author": "miodf",
"author_id": 457557,
"author_profile": "https://Stackoverflow.com/users/457557",
"pm_score": 2,
"selected": false,
"text": "<p>For newbees, these links explains how to do an automatic profiling of all the subs that you want to time monitor :</p>\n\n<p><a href=\"http://www.nullskull.com/a/1602/profiling-and-optimizing-vba.aspx\" rel=\"nofollow\">http://www.nullskull.com/a/1602/profiling-and-optimizing-vba.aspx</a></p>\n\n<p><a href=\"http://sites.mcpher.com/share/Home/excelquirks/optimizationlink\" rel=\"nofollow\">http://sites.mcpher.com/share/Home/excelquirks/optimizationlink</a>\nsee procProfiler.zip in <a href=\"http://sites.mcpher.com/share/Home/excelquirks/downlable-items\" rel=\"nofollow\">http://sites.mcpher.com/share/Home/excelquirks/downlable-items</a></p>\n"
},
{
"answer_id": 58006854,
"author": "Gajendra Santosh",
"author_id": 9561828,
"author_profile": "https://Stackoverflow.com/users/9561828",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Sub Macro1()\n Dim StartTime As Double\n StartTime = Timer\n\n ''''''''''''''''''''\n 'Your Code'\n ''''''''''''''''''''\n MsgBox \"RunTime : \" & Format((Timer - StartTime) / 86400, \"hh:mm:ss\")\nEnd Sub\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>RunTime : 00:00:02</p>\n</blockquote>\n"
},
{
"answer_id": 61219046,
"author": "SendETHToThisAddress",
"author_id": 5835002,
"author_profile": "https://Stackoverflow.com/users/5835002",
"pm_score": 1,
"selected": false,
"text": "<p>Seconds with 2 decimal spaces:</p>\n\n<pre><code>Dim startTime As Single 'start timer\nMsgBox (\"run time: \" & Format((Timer - startTime) / 1000000, \"#,##0.00\") & \" seconds\") 'end timer\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/YgQWt.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YgQWt.jpg\" alt=\"seconds format\"></a></p>\n\n<p>Milliseconds:</p>\n\n<pre><code>Dim startTime As Single 'start timer\nMsgBox (\"run time: \" & Format((Timer - startTime), \"#,##0.00\") & \" milliseconds\") 'end timer\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/xy9JG.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xy9JG.jpg\" alt=\"milliseconds format\"></a></p>\n\n<p>Milliseconds with comma seperator:</p>\n\n<pre><code>Dim startTime As Single 'start timer\nMsgBox (\"run time: \" & Format((Timer - startTime) * 1000, \"#,##0.00\") & \" milliseconds\") 'end timer\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/LM9CF.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LM9CF.jpg\" alt=\"Milliseconds with comma seperator\"></a></p>\n\n<p>Just leaving this here for anyone that was looking for a simple timer formatted with seconds to 2 decimal spaces like I was. These are short and sweet little timers I like to use. They only take up one line of code at the beginning of the sub or function and one line of code again at the end. These aren't meant to be crazy accurate, I generally don't care about anything less then 1/100th of a second personally, but the milliseconds timer will give you the most accurate run time of these 3. I've also read you can get the incorrect read out if it happens to run while crossing over midnight, a rare instance but just FYI.</p>\n"
},
{
"answer_id": 68406681,
"author": "jonadv",
"author_id": 6544310,
"author_profile": "https://Stackoverflow.com/users/6544310",
"pm_score": 2,
"selected": false,
"text": "<p>As Mike Woodhouse answered the QueryPerformanceCounter function is the most accurate possible way to bench VBA code (when you don't want to use a custom made dll). I wrote a class (link <a href=\"https://github.com/jonadv/VBA-Benchmark\" rel=\"nofollow noreferrer\">https://github.com/jonadv/VBA-Benchmark</a>) that makes that function easy to use:</p>\n<ol>\n<li>only initialize the benchmark class</li>\n<li>call the method in between your code.</li>\n</ol>\n<p>There is no need to write code for substracting times, re-initializing times and writing to debug for example.</p>\n<pre><code>Sub TimerBenchmark()\n\nDim bm As New cBenchmark\n\n'Some code here\nbm.TrackByName "Some code"\n\nEnd Sub\n</code></pre>\n<p>This would automatically print a readable table to the Immediate window:</p>\n<pre><code>IDnr Name Count Sum of tics Percentage Time sum\n0 Some code 1 163 100,00% 16 us\n TOTAL 1 163 100,00% 16 us\n\nTotal time recorded: 16 us\n</code></pre>\n<p>Ofcourse with only one piece of code the table isnt very usefull, but with multiple pieces of code, it instantly becomes clear where the bottleneck in your code is. The class includes a .Wait function, which does the same as Application.Wait, but requires only an input in seconds, instead of a time value (which takes a lot of characters to code).</p>\n<pre><code>Sub TimerBenchmark()\n\nDim bm As New cBenchmark\n\nbm.Wait 0.0001 'Simulation of some code\nbm.TrackByName "Some code"\n\nbm.Wait 0.04 'Simulation of some (time consuming) code here\nbm.TrackByName "Bottleneck code"\n\n\nbm.Wait 0.00004 'Simulation of some code, with the same tag as above\nbm.TrackByName "Some code"\n\nEnd Sub\n</code></pre>\n<p>Prints a table with percentages and summarizes code with the same name/tag:</p>\n<pre><code>IDnr Name Count Sum of tics Percentage Time sum\n0 Some code 2 21.374 5,07% 2,14 ms\n1 Bottleneck code 1 400.395 94,93% 40 ms\n TOTAL 3 421.769 100,00% 42 ms\n\nTotal time recorded: 42 ms\n</code></pre>\n"
},
{
"answer_id": 71786637,
"author": "Daekar",
"author_id": 11964259,
"author_profile": "https://Stackoverflow.com/users/11964259",
"pm_score": 1,
"selected": false,
"text": "<p>I read other answers in this thread and threw together my own class to handle things. It's more an exercise in making a class than anything, but it does work and offers precision at the level I need for my work... I'm just making office tools.</p>\n<p>To use the class, you do a dim statement, instantiate a new object when you want to start the timer, and then call a method to stop the timer and get output. Taking a cue from Jonadv's example, there is an optional argument to allow you to label the output in instances where you use multiple timers at once.</p>\n<p>Just put this in a class named cTimer:</p>\n<pre><code>Option Explicit\n\n'This class allows you to easily see how long your code takes to run by encapsulating the Timer function, which returns the time since midnight in seconds.\n'Instantiate the class to start the clock and use the StopTimer method to stop it and output to the Immediate window. It will accept an optional argument to label the timer.\n'If you want to use it multiple times in the same program, make sure to terminate it before creating another timer.\n\n'EXAMPLE:\n'Sub ExampleSub()\n'Dim t As cTimer 'Declare t as a member of the cTimer class\n'Set t = New cTimer 'Create a new cTimer class object called "t" and set the start time\n'...\n'...\n'...\n'some code\n'...\n'...\n'...\n't.StopTimer 'Set the stop time and output elapsed time to the Immediate window. This will output "Timed process took X.XXXXX seconds"\n'Set t = Nothing 'Destroy the existing cTimer object called "t"\n'Set t = New cTimer 'Create a new cTimer class object called "t" and set the start time again.\n'...\n'...\n'...\n'some code\n'...\n'...\n'...\n't.StopTimer ("Second section") 'Set the stop time once more and output elapsed time to the Immediate window. The text output will read "Second section: X.XXXX seconds" for this line.\n'End Sub\n\n\nPrivate pStartTime As Single\nPrivate pEndTime As Single\n\nPrivate Sub Class_Initialize()\npStartTime = Timer\nEnd Sub\n\nPublic Sub StopTimer(Optional SectionName As String)\npEndTime = Timer\nIf Not SectionName = "" Then 'If user defines the optional SectionName string\n Debug.Print SectionName & ": " & (pEndTime - pStartTime) & " seconds"\nElse\n Debug.Print "Timed process took " & (pEndTime - pStartTime) & " seconds"\nEnd If\nEnd Sub\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
] |
Is there code in VBA I can wrap a function with that will let me know the time it took to run, so that I can compare the different running times of functions?
|
Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is `QueryPerformanceCounter`. Google it for more info. Try pushing the following into a class, call it `CTimer` say, then you can make an instance somewhere global and just call `.StartCounter` and `.TimeElapsed`
```
Option Explicit
Private Type LARGE_INTEGER
lowpart As Long
highpart As Long
End Type
Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long
Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double
Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#
Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
Low = LI.lowpart
If Low < 0 Then
Low = Low + TWO_32
End If
LI2Double = LI.highpart * TWO_32 + Low
End Function
Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
QueryPerformanceFrequency PerfFrequency
m_crFrequency = LI2Double(PerfFrequency)
End Sub
Public Sub StartCounter()
QueryPerformanceCounter m_CounterStart
End Sub
Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
QueryPerformanceCounter m_CounterEnd
crStart = LI2Double(m_CounterStart)
crStop = LI2Double(m_CounterEnd)
TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property
```
|
198,431 |
<p>Is there a standard idiom for comparing version numbers? I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be. I need to compare the versions and have the following hold true:</p>
<pre><code>1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
</code></pre>
|
[
{
"answer_id": 198442,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 7,
"selected": true,
"text": "<p>Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.</p>\n"
},
{
"answer_id": 836665,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 6,
"selected": false,
"text": "<p>You need to normalise the version strings so they can be compared. Something like</p>\n\n<pre><code>import java.util.regex.Pattern;\n\npublic class Main {\n public static void main(String... args) {\n compare(\"1.0\", \"1.1\");\n compare(\"1.0.1\", \"1.1\");\n compare(\"1.9\", \"1.10\");\n compare(\"1.a\", \"1.9\");\n }\n\n private static void compare(String v1, String v2) {\n String s1 = normalisedVersion(v1);\n String s2 = normalisedVersion(v2);\n int cmp = s1.compareTo(s2);\n String cmpStr = cmp < 0 ? \"<\" : cmp > 0 ? \">\" : \"==\";\n System.out.printf(\"'%s' %s '%s'%n\", v1, cmpStr, v2);\n }\n\n public static String normalisedVersion(String version) {\n return normalisedVersion(version, \".\", 4);\n }\n\n public static String normalisedVersion(String version, String sep, int maxWidth) {\n String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);\n StringBuilder sb = new StringBuilder();\n for (String s : split) {\n sb.append(String.format(\"%\" + maxWidth + 's', s));\n }\n return sb.toString();\n }\n}\n</code></pre>\n\n<p>Prints</p>\n\n<blockquote>\n<pre><code>'1.0' < '1.1'\n'1.0.1' < '1.1'\n'1.9' < '1.10'\n'1.a' > '1.9'\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 2031954,
"author": "Cenk Alti",
"author_id": 242451,
"author_profile": "https://Stackoverflow.com/users/242451",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public int compare(String v1, String v2) {\n v1 = v1.replaceAll(\"\\\\s\", \"\");\n v2 = v2.replaceAll(\"\\\\s\", \"\");\n String[] a1 = v1.split(\"\\\\.\");\n String[] a2 = v2.split(\"\\\\.\");\n List<String> l1 = Arrays.asList(a1);\n List<String> l2 = Arrays.asList(a2);\n\n\n int i=0;\n while(true){\n Double d1 = null;\n Double d2 = null;\n\n try{\n d1 = Double.parseDouble(l1.get(i));\n }catch(IndexOutOfBoundsException e){\n }\n\n try{\n d2 = Double.parseDouble(l2.get(i));\n }catch(IndexOutOfBoundsException e){\n }\n\n if (d1 != null && d2 != null) {\n if (d1.doubleValue() > d2.doubleValue()) {\n return 1;\n } else if (d1.doubleValue() < d2.doubleValue()) {\n return -1;\n }\n } else if (d2 == null && d1 != null) {\n if (d1.doubleValue() > 0) {\n return 1;\n }\n } else if (d1 == null && d2 != null) {\n if (d2.doubleValue() > 0) {\n return -1;\n }\n } else {\n break;\n }\n i++;\n }\n return 0;\n }\n</code></pre>\n"
},
{
"answer_id": 6640972,
"author": "Alex Dean",
"author_id": 255627,
"author_profile": "https://Stackoverflow.com/users/255627",
"pm_score": 7,
"selected": false,
"text": "<p>It's really easy using Maven:</p>\n\n<pre><code>import org.apache.maven.artifact.versioning.DefaultArtifactVersion;\n\nDefaultArtifactVersion minVersion = new DefaultArtifactVersion(\"1.0.1\");\nDefaultArtifactVersion maxVersion = new DefaultArtifactVersion(\"1.10\");\n\nDefaultArtifactVersion version = new DefaultArtifactVersion(\"1.11\");\n\nif (version.compareTo(minVersion) < 0 || version.compareTo(maxVersion) > 0) {\n System.out.println(\"Sorry, your version is unsupported\");\n}\n</code></pre>\n\n<p>You can get the right dependency string for Maven Artifact from <a href=\"http://mvnrepository.com/artifact/org.apache.maven/maven-artifact/3.0.3\" rel=\"noreferrer\">this page</a>:</p>\n\n<pre><code><dependency>\n<groupId>org.apache.maven</groupId>\n<artifactId>maven-artifact</artifactId>\n<version>3.0.3</version>\n</dependency>\n</code></pre>\n"
},
{
"answer_id": 10034633,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 5,
"selected": false,
"text": "<pre><code>// VersionComparator.java\nimport java.util.Comparator;\n\npublic class VersionComparator implements Comparator {\n\n public boolean equals(Object o1, Object o2) {\n return compare(o1, o2) == 0;\n }\n\n public int compare(Object o1, Object o2) {\n String version1 = (String) o1;\n String version2 = (String) o2;\n\n VersionTokenizer tokenizer1 = new VersionTokenizer(version1);\n VersionTokenizer tokenizer2 = new VersionTokenizer(version2);\n\n int number1 = 0, number2 = 0;\n String suffix1 = \"\", suffix2 = \"\";\n\n while (tokenizer1.MoveNext()) {\n if (!tokenizer2.MoveNext()) {\n do {\n number1 = tokenizer1.getNumber();\n suffix1 = tokenizer1.getSuffix();\n if (number1 != 0 || suffix1.length() != 0) {\n // Version one is longer than number two, and non-zero\n return 1;\n }\n }\n while (tokenizer1.MoveNext());\n\n // Version one is longer than version two, but zero\n return 0;\n }\n\n number1 = tokenizer1.getNumber();\n suffix1 = tokenizer1.getSuffix();\n number2 = tokenizer2.getNumber();\n suffix2 = tokenizer2.getSuffix();\n\n if (number1 < number2) {\n // Number one is less than number two\n return -1;\n }\n if (number1 > number2) {\n // Number one is greater than number two\n return 1;\n }\n\n boolean empty1 = suffix1.length() == 0;\n boolean empty2 = suffix2.length() == 0;\n\n if (empty1 && empty2) continue; // No suffixes\n if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)\n if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)\n\n // Lexical comparison of suffixes\n int result = suffix1.compareTo(suffix2);\n if (result != 0) return result;\n\n }\n if (tokenizer2.MoveNext()) {\n do {\n number2 = tokenizer2.getNumber();\n suffix2 = tokenizer2.getSuffix();\n if (number2 != 0 || suffix2.length() != 0) {\n // Version one is longer than version two, and non-zero\n return -1;\n }\n }\n while (tokenizer2.MoveNext());\n\n // Version two is longer than version one, but zero\n return 0;\n }\n return 0;\n }\n}\n\n// VersionTokenizer.java\npublic class VersionTokenizer {\n private final String _versionString;\n private final int _length;\n\n private int _position;\n private int _number;\n private String _suffix;\n private boolean _hasValue;\n\n public int getNumber() {\n return _number;\n }\n\n public String getSuffix() {\n return _suffix;\n }\n\n public boolean hasValue() {\n return _hasValue;\n }\n\n public VersionTokenizer(String versionString) {\n if (versionString == null)\n throw new IllegalArgumentException(\"versionString is null\");\n\n _versionString = versionString;\n _length = versionString.length();\n }\n\n public boolean MoveNext() {\n _number = 0;\n _suffix = \"\";\n _hasValue = false;\n\n // No more characters\n if (_position >= _length)\n return false;\n\n _hasValue = true;\n\n while (_position < _length) {\n char c = _versionString.charAt(_position);\n if (c < '0' || c > '9') break;\n _number = _number * 10 + (c - '0');\n _position++;\n }\n\n int suffixStart = _position;\n\n while (_position < _length) {\n char c = _versionString.charAt(_position);\n if (c == '.') break;\n _position++;\n }\n\n _suffix = _versionString.substring(suffixStart, _position);\n\n if (_position < _length) _position++;\n\n return true;\n }\n}\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>public class Main\n{\n private static VersionComparator cmp;\n\n public static void main (String[] args)\n {\n cmp = new VersionComparator();\n Test(new String[]{\"1.1.2\", \"1.2\", \"1.2.0\", \"1.2.1\", \"1.12\"});\n Test(new String[]{\"1.3\", \"1.3a\", \"1.3b\", \"1.3-SNAPSHOT\"});\n }\n\n private static void Test(String[] versions) {\n for (int i = 0; i < versions.length; i++) {\n for (int j = i; j < versions.length; j++) {\n Test(versions[i], versions[j]);\n }\n }\n }\n\n private static void Test(String v1, String v2) {\n int result = cmp.compare(v1, v2);\n String op = \"==\";\n if (result < 0) op = \"<\";\n if (result > 0) op = \">\";\n System.out.printf(\"%s %s %s\\n\", v1, op, v2);\n }\n}\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>1.1.2 == 1.1.2 ---> same length and value\n1.1.2 < 1.2 ---> first number (1) less than second number (2) => -1\n1.1.2 < 1.2.0 ---> first number (1) less than second number (2) => -1\n1.1.2 < 1.2.1 ---> first number (1) less than second number (2) => -1\n1.1.2 < 1.12 ---> first number (1) less than second number (12) => -1\n1.2 == 1.2 ---> same length and value\n1.2 == 1.2.0 ---> first shorter than second, but zero\n1.2 < 1.2.1 ---> first shorter than second, and non-zero\n1.2 < 1.12 ---> first number (2) less than second number (12) => -1\n1.2.0 == 1.2.0 ---> same length and value\n1.2.0 < 1.2.1 ---> first number (0) less than second number (1) => -1\n1.2.0 < 1.12 ---> first number (2) less than second number (12) => -1\n1.2.1 == 1.2.1 ---> same length and value\n1.2.1 < 1.12 ---> first number (2) less than second number (12) => -1\n1.12 == 1.12 ---> same length and value\n\n1.3 == 1.3 ---> same length and value\n1.3 > 1.3a ---> first suffix ('') is empty, but not second ('a') => 1\n1.3 > 1.3b ---> first suffix ('') is empty, but not second ('b') => 1\n1.3 > 1.3-SNAPSHOT ---> first suffix ('') is empty, but not second ('-SNAPSHOT') => 1\n1.3a == 1.3a ---> same length and value\n1.3a < 1.3b ---> first suffix ('a') compared to second suffix ('b') => -1\n1.3a < 1.3-SNAPSHOT ---> first suffix ('a') compared to second suffix ('-SNAPSHOT') => -1\n1.3b == 1.3b ---> same length and value\n1.3b < 1.3-SNAPSHOT ---> first suffix ('b') compared to second suffix ('-SNAPSHOT') => -1\n1.3-SNAPSHOT == 1.3-SNAPSHOT ---> same length and value\n</code></pre>\n"
},
{
"answer_id": 11024200,
"author": "alex",
"author_id": 1445568,
"author_profile": "https://Stackoverflow.com/users/1445568",
"pm_score": 8,
"selected": false,
"text": "<p>Another solution for this old post (for those that it might help) :</p>\n\n<pre><code>public class Version implements Comparable<Version> {\n\n private String version;\n\n public final String get() {\n return this.version;\n }\n\n public Version(String version) {\n if(version == null)\n throw new IllegalArgumentException(\"Version can not be null\");\n if(!version.matches(\"[0-9]+(\\\\.[0-9]+)*\"))\n throw new IllegalArgumentException(\"Invalid version format\");\n this.version = version;\n }\n\n @Override public int compareTo(Version that) {\n if(that == null)\n return 1;\n String[] thisParts = this.get().split(\"\\\\.\");\n String[] thatParts = that.get().split(\"\\\\.\");\n int length = Math.max(thisParts.length, thatParts.length);\n for(int i = 0; i < length; i++) {\n int thisPart = i < thisParts.length ?\n Integer.parseInt(thisParts[i]) : 0;\n int thatPart = i < thatParts.length ?\n Integer.parseInt(thatParts[i]) : 0;\n if(thisPart < thatPart)\n return -1;\n if(thisPart > thatPart)\n return 1;\n }\n return 0;\n }\n\n @Override public boolean equals(Object that) {\n if(this == that)\n return true;\n if(that == null)\n return false;\n if(this.getClass() != that.getClass())\n return false;\n return this.compareTo((Version) that) == 0;\n }\n\n}\n</code></pre>\n\n<hr>\n\n<pre><code>Version a = new Version(\"1.1\");\nVersion b = new Version(\"1.1.1\");\na.compareTo(b) // return -1 (a<b)\na.equals(b) // return false\n\nVersion a = new Version(\"2.0\");\nVersion b = new Version(\"1.9.9\");\na.compareTo(b) // return 1 (a>b)\na.equals(b) // return false\n\nVersion a = new Version(\"1.0\");\nVersion b = new Version(\"1\");\na.compareTo(b) // return 0 (a=b)\na.equals(b) // return true\n\nVersion a = new Version(\"1\");\nVersion b = null;\na.compareTo(b) // return 1 (a>b)\na.equals(b) // return false\n\nList<Version> versions = new ArrayList<Version>();\nversions.add(new Version(\"2\"));\nversions.add(new Version(\"1.0.5\"));\nversions.add(new Version(\"1.01.0\"));\nversions.add(new Version(\"1.00.1\"));\nCollections.min(versions).get() // return min version\nCollections.max(versions).get() // return max version\n\n// WARNING\nVersion a = new Version(\"2.06\");\nVersion b = new Version(\"2.060\");\na.equals(b) // return false\n</code></pre>\n\n<hr>\n\n<p>Edit:</p>\n\n<p>@daiscog: Thank you for your remark, this piece of code has been developed for the Android platform and as recommended by Google, the method \"matches\" check the entire string unlike Java that uses a regulatory pattern. (<a href=\"http://developer.android.com/reference/java/lang/String.html#matches%28java.lang.String%29\">Android documentation</a> - <a href=\"http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#matches%28java.lang.String%29\">JAVA documentation</a>)</p>\n"
},
{
"answer_id": 14591442,
"author": "petrnohejl",
"author_id": 686540,
"author_profile": "https://Stackoverflow.com/users/686540",
"pm_score": 1,
"selected": false,
"text": "<p>I created simple <a href=\"https://github.com/petrnohejl/Alfonz/blob/master/alfonz-utility/src/main/java/org/alfonz/utility/VersionUtility.java\" rel=\"nofollow noreferrer\"><strong>utility for comparing versions</strong></a> on <strong>Android platform</strong> using <a href=\"http://semver.org/\" rel=\"nofollow noreferrer\"><strong>Semantic Versioning</strong></a> convention. So it works only for strings in format X.Y.Z (Major.Minor.Patch) where X, Y, and Z are non-negative integers. You can find it on my <a href=\"https://github.com/petrnohejl/Alfonz/blob/master/alfonz-utility/src/main/java/org/alfonz/utility/VersionUtility.java\" rel=\"nofollow noreferrer\">GitHub</a>.</p>\n\n<p>Method <em>Version.compareVersions(String v1, String v2)</em> compares two version strings. It returns 0 if the versions are equal, 1 if version v1 is before version v2, -1 if version v1 is after version v2, -2 if version format is invalid.</p>\n"
},
{
"answer_id": 26745775,
"author": "Ryszard Perkowski",
"author_id": 2698854,
"author_profile": "https://Stackoverflow.com/users/2698854",
"pm_score": 6,
"selected": false,
"text": "<p>The best to reuse existing code,\ntake <a href=\"http://grepcode.com/file_/repo1.maven.org/maven2/org.apache.maven/maven-artifact/3.2.3/org/apache/maven/artifact/versioning/ComparableVersion.java/?v=source\">Maven's ComparableVersion class</a></p>\n\n<p>advantages:</p>\n\n<ul>\n<li>Apache License, Version 2.0, </li>\n<li>tested, </li>\n<li>used (copied) in multiple projects like spring-security-core, jboss etc</li>\n<li>multiple <a href=\"https://maven.apache.org/ref/3.0.4/maven-artifact/apidocs/org/apache/maven/artifact/versioning/ComparableVersion.html\">features</a></li>\n<li>it's already a java.lang.Comparable</li>\n<li>just copy-paste that one class, no third-party dependencies</li>\n</ul>\n\n<p>Don't include dependency to maven-artifact as that will pull various transitive dependencies</p>\n"
},
{
"answer_id": 27109234,
"author": "sfrizvi6",
"author_id": 4288292,
"author_profile": "https://Stackoverflow.com/users/4288292",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public class VersionComparator {\n\n /* loop through both version strings\n * then loop through the inner string to computer the val of the int\n * for each integer read, do num*10+<integer read>\n * and stop when stumbling upon '.'\n * When '.' is encountered...\n * see if '.' is encountered for both strings\n * if it is then compare num1 and num2 \n * if num1 == num2... iterate over p1++, p2++\n * else return (num1 > num2) ? 1 : -1\n * If both the string end then compare(num1, num2) return 0, 1, -1\n * else loop through the longer string and \n * verify if it only has trailing zeros\n * If it only has trailing zeros then return 0\n * else it is greater than the other string\n */\n public static int compareVersions(String v1, String v2) {\n int num1 = 0;\n int num2 = 0;\n int p1 = 0;\n int p2 = 0;\n\n while (p1 < v1.length() && p2 < v2.length()) {\n num1 = Integer.parseInt(v1.charAt(p1) + \"\");\n num2 = Integer.parseInt(v2.charAt(p2) + \"\");\n p1++;\n p2++;\n\n while (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) != '.' && v2.charAt(p2) != '.') {\n if (p1 < v1.length()) num1 = num1 * 10 + Integer.parseInt(v1.charAt(p1) + \"\");\n if (p2 < v2.length()) num2 = num2 * 10 + Integer.parseInt(v2.charAt(p2) + \"\");\n p1++;\n p2++;\n }\n\n if (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) == '.' && v2.charAt(p2) == '.') {\n if ((num1 ^ num2) == 0) {\n p1++;\n p2++;\n }\n else return (num1 > num2) ? 1 : -1;\n }\n else if (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) == '.') return -1;\n else if (p1 < v1.length() && p2 < v2.length() && v2.charAt(p2) == '.') return 1;\n }\n\n if (p1 == v1.length() && p2 == v2.length()) {\n if ((num1 ^ num2) == 0) return 0;\n else return (num1 > num2) ? 1 : -1;\n }\n else if (p1 == v1.length()) {\n if ((num1 ^ num2) == 0) {\n while (p2 < v2.length()) {\n if (v2.charAt(p2) != '.' && v2.charAt(p2) != '0') return -1;\n p2++;\n }\n return 0;\n }\n else return (num1 > num2) ? 1 : -1;\n }\n else {\n if ((num1 ^ num2) == 0) {\n while (p1 < v1.length()) {\n if (v1.charAt(p1) != '.' && v1.charAt(p1) != '0') return 1;\n p1++;\n }\n return 0;\n }\n else return (num1 > num2) ? 1 : -1;\n }\n }\n\n public static void main(String[] args) {\n System.out.println(compareVersions(\"11.23\", \"11.21.1.0.0.1.0\") ^ 1);\n System.out.println(compareVersions(\"11.21.1.0.0.1.0\", \"11.23\") ^ -1);\n System.out.println(compareVersions(\"11.23\", \"11.23.0.0.0.1.0\") ^ -1);\n System.out.println(compareVersions(\"11.2\", \"11.23\") ^ -1);\n System.out.println(compareVersions(\"11.23\", \"11.21.1.0.0.1.0\") ^ 1);\n System.out.println(compareVersions(\"1.21.1.0.0.1.0\", \"2.23\") ^ -1);\n System.out.println(compareVersions(\"11.23\", \"11.21.1.0.0.1.0\") ^ 1);\n System.out.println(compareVersions(\"11.23.0.0.0.0.0\", \"11.23\") ^ 0);\n System.out.println(compareVersions(\"11.23\", \"11.21.1.0.0.1.0\") ^ 1);\n System.out.println(compareVersions(\"1.5.1.3\", \"1.5.1.3.0\") ^ 0);\n System.out.println(compareVersions(\"1.5.1.4\", \"1.5.1.3.0\") ^ 1);\n System.out.println(compareVersions(\"1.2.1.3\", \"1.5.1.3.0\") ^ -1);\n System.out.println(compareVersions(\"1.2.1.3\", \"1.22.1.3.0\") ^ -1);\n System.out.println(compareVersions(\"1.222.1.3\", \"1.22.1.3.0\") ^ 1);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27891752,
"author": "Algorithmatic",
"author_id": 1122229,
"author_profile": "https://Stackoverflow.com/users/1122229",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public static int compareVersions(String version1, String version2){\n\n String[] levels1 = version1.split(\"\\\\.\");\n String[] levels2 = version2.split(\"\\\\.\");\n\n int length = Math.max(levels1.length, levels2.length);\n for (int i = 0; i < length; i++){\n Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;\n Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;\n int compare = v1.compareTo(v2);\n if (compare != 0){\n return compare;\n }\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 31103694,
"author": "ballzak",
"author_id": 445360,
"author_profile": "https://Stackoverflow.com/users/445360",
"pm_score": -1,
"selected": false,
"text": "<p>Here's an optimized implementation:</p>\n\n<pre><code>public static final Comparator<CharSequence> VERSION_ORDER = new Comparator<CharSequence>() {\n\n @Override\n public int compare (CharSequence lhs, CharSequence rhs) {\n int ll = lhs.length(), rl = rhs.length(), lv = 0, rv = 0, li = 0, ri = 0;\n char c;\n do {\n lv = rv = 0;\n while (--ll >= 0) {\n c = lhs.charAt(li++);\n if (c < '0' || c > '9')\n break;\n lv = lv*10 + c - '0';\n }\n while (--rl >= 0) {\n c = rhs.charAt(ri++);\n if (c < '0' || c > '9')\n break;\n rv = rv*10 + c - '0';\n }\n } while (lv == rv && (ll >= 0 || rl >= 0));\n return lv - rv;\n }\n\n};\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>\"0.1\" - \"1.0\" = -1\n\"1.0\" - \"1.0\" = 0\n\"1.0\" - \"1.0.0\" = 0\n\"10\" - \"1.0\" = 9\n\"3.7.6\" - \"3.7.11\" = -5\n\"foobar\" - \"1.0\" = -1\n</code></pre>\n"
},
{
"answer_id": 36431997,
"author": "gorums",
"author_id": 1327403,
"author_profile": "https://Stackoverflow.com/users/1327403",
"pm_score": -1,
"selected": false,
"text": "<p>This code try to resolve this type of comparison versions.</p>\n\n<blockquote>\n <p>Most of the version specifiers, like >= 1.0, are self-explanatory. The\n specifier ~> has a special meaning, best shown by example. ~> 2.0.3 is\n identical to >= 2.0.3 and < 2.1. ~> 2.1 is identical to >= 2.1 and <\n 3.0.</p>\n</blockquote>\n\n<pre><code>public static boolean apply(String cmpDeviceVersion, String reqDeviceVersion)\n{\n Boolean equal = !cmpDeviceVersion.contains(\">\") && !cmpDeviceVersion.contains(\">=\") &&\n !cmpDeviceVersion.contains(\"<\") && !cmpDeviceVersion.contains(\"<=\") &&\n !cmpDeviceVersion.contains(\"~>\");\n\n Boolean between = cmpDeviceVersion.contains(\"~>\");\n Boolean higher = cmpDeviceVersion.contains(\">\") && !cmpDeviceVersion.contains(\">=\") && !cmpDeviceVersion.contains(\"~>\");\n Boolean higherOrEqual = cmpDeviceVersion.contains(\">=\");\n\n Boolean less = cmpDeviceVersion.contains(\"<\") && !cmpDeviceVersion.contains(\"<=\");\n Boolean lessOrEqual = cmpDeviceVersion.contains(\"<=\");\n\n cmpDeviceVersion = cmpDeviceVersion.replaceAll(\"[<>=~]\", \"\");\n cmpDeviceVersion = cmpDeviceVersion.trim();\n\n String[] version = cmpDeviceVersion.split(\"\\\\.\");\n String[] reqVersion = reqDeviceVersion.split(\"\\\\.\");\n\n if(equal)\n {\n return isEqual(version, reqVersion);\n }\n else if(between)\n {\n return isBetween(version, reqVersion);\n }\n else if(higher)\n {\n return isHigher(version, reqVersion);\n }\n else if(higherOrEqual)\n {\n return isEqual(version, reqVersion) || isHigher(version, reqVersion);\n }\n else if(less)\n {\n return isLess(version, reqVersion);\n }\n else if(lessOrEqual)\n {\n return isEqual(version, reqVersion) || isLess(version, reqVersion);\n }\n\n return false;\n}\n\nprivate static boolean isEqual(String[] version, String[] reqVersion)\n{\n String strVersion = StringUtils.join(version);\n String strReqVersion = StringUtils.join(reqVersion);\n if(version.length > reqVersion.length)\n {\n Integer diff = version.length - reqVersion.length;\n strReqVersion += StringUtils.repeat(\".0\", diff);\n }\n else if(reqVersion.length > version.length)\n {\n Integer diff = reqVersion.length - version.length;\n strVersion += StringUtils.repeat(\".0\", diff);\n }\n\n return strVersion.equals(strReqVersion);\n}\n\nprivate static boolean isHigher(String[] version, String[] reqVersion)\n{\n String strVersion = StringUtils.join(version);\n String strReqVersion = StringUtils.join(reqVersion);\n if(version.length > reqVersion.length)\n {\n Integer diff = version.length - reqVersion.length;\n strReqVersion += StringUtils.repeat(\".0\", diff);\n }\n else if(reqVersion.length > version.length)\n {\n Integer diff = reqVersion.length - version.length;\n strVersion += StringUtils.repeat(\".0\", diff);\n }\n\n return strReqVersion.compareTo(strVersion) > 0;\n}\n\nprivate static boolean isLess(String[] version, String[] reqVersion)\n{\n String strVersion = StringUtils.join(version);\n String strReqVersion = StringUtils.join(reqVersion);\n if(version.length > reqVersion.length)\n {\n Integer diff = version.length - reqVersion.length;\n strReqVersion += StringUtils.repeat(\".0\", diff);\n }\n else if(reqVersion.length > version.length)\n {\n Integer diff = reqVersion.length - version.length;\n strVersion += StringUtils.repeat(\".0\", diff);\n }\n\n return strReqVersion.compareTo(strVersion) < 0;\n}\n\nprivate static boolean isBetween(String[] version, String[] reqVersion)\n{\n return (isEqual(version, reqVersion) || isHigher(version, reqVersion)) &&\n isLess(getNextVersion(version), reqVersion);\n}\n\nprivate static String[] getNextVersion(String[] version)\n{\n String[] nextVersion = new String[version.length];\n for(int i = version.length - 1; i >= 0 ; i--)\n {\n if(i == version.length - 1)\n {\n nextVersion[i] = \"0\";\n }\n else if((i == version.length - 2) && NumberUtils.isNumber(version[i]))\n {\n nextVersion[i] = String.valueOf(NumberUtils.toInt(version[i]) + 1);\n }\n else\n {\n nextVersion[i] = version[i];\n }\n }\n return nextVersion;\n}\n</code></pre>\n"
},
{
"answer_id": 37593558,
"author": "Igor Maznitsa",
"author_id": 1802697,
"author_profile": "https://Stackoverflow.com/users/1802697",
"pm_score": 1,
"selected": false,
"text": "<p>for my projects I use my commons-version library <a href=\"https://github.com/raydac/commons-version\" rel=\"nofollow\">https://github.com/raydac/commons-version</a>\nit contains two auxiliary classes - to parse version (parsed version can be compared with another version object because it is comparable one) and VersionValidator which allows to check version for some expression like <code>!=ide-1.1.1,>idea-1.3.4-SNAPSHOT;<1.2.3</code></p>\n"
},
{
"answer_id": 40089814,
"author": "Alex",
"author_id": 288568,
"author_profile": "https://Stackoverflow.com/users/288568",
"pm_score": 5,
"selected": false,
"text": "<p>Wondering why everybody assumes that the versions is only made up of integers - in my case it was not.</p>\n\n<p>Why reinventing the wheel (assuming the version follows the Semver standard)</p>\n\n<p>First install <a href=\"https://github.com/vdurmont/semver4j\" rel=\"noreferrer\">https://github.com/vdurmont/semver4j</a> via Maven</p>\n\n<p>Then use this library</p>\n\n<pre><code>Semver sem = new Semver(\"1.2.3\");\nsem.isGreaterThan(\"1.2.2\"); // true\n</code></pre>\n"
},
{
"answer_id": 41530729,
"author": "Abhinav Puri",
"author_id": 4370675,
"author_profile": "https://Stackoverflow.com/users/4370675",
"pm_score": -1,
"selected": false,
"text": "<p>I liked the idea from @Peter Lawrey, And i extended it to further limits : </p>\n\n<pre><code> /**\n * Normalize string array, \n * Appends zeros if string from the array\n * has length smaller than the maxLen.\n **/\n private String normalize(String[] split, int maxLen){\n StringBuilder sb = new StringBuilder(\"\");\n for(String s : split) {\n for(int i = 0; i<maxLen-s.length(); i++) sb.append('0');\n sb.append(s);\n }\n return sb.toString();\n }\n\n /**\n * Removes trailing zeros of the form '.00.0...00'\n * (and does not remove zeros from, say, '4.1.100')\n **/\n public String removeTrailingZeros(String s){\n int i = s.length()-1;\n int k = s.length()-1;\n while(i >= 0 && (s.charAt(i) == '.' || s.charAt(i) == '0')){\n if(s.charAt(i) == '.') k = i-1;\n i--; \n } \n return s.substring(0,k+1);\n }\n\n /**\n * Compares two versions(works for alphabets too),\n * Returns 1 if v1 > v2, returns 0 if v1 == v2,\n * and returns -1 if v1 < v2.\n **/\n public int compareVersion(String v1, String v2) {\n\n // Uncomment below two lines if for you, say, 4.1.0 is equal to 4.1\n // v1 = removeTrailingZeros(v1);\n // v2 = removeTrailingZeros(v2);\n\n String[] splitv1 = v1.split(\"\\\\.\");\n String[] splitv2 = v2.split(\"\\\\.\");\n int maxLen = 0;\n for(String str : splitv1) maxLen = Math.max(maxLen, str.length());\n for(String str : splitv2) maxLen = Math.max(maxLen, str.length());\n int cmp = normalize(splitv1, maxLen).compareTo(normalize(splitv2, maxLen));\n return cmp > 0 ? 1 : (cmp < 0 ? -1 : 0);\n }\n</code></pre>\n\n<p>Hope it helps someone. It passed all test cases in interviewbit and leetcode (need to uncomment two lines in compareVersion function). </p>\n\n<p>Easily tested !</p>\n"
},
{
"answer_id": 42311661,
"author": "Arpan Sharma",
"author_id": 5954472,
"author_profile": "https://Stackoverflow.com/users/5954472",
"pm_score": 0,
"selected": false,
"text": "<p>Wrote a little function myself.Simpler Using Lists</p>\n\n<pre><code> public static boolean checkVersionUpdate(String olderVerison, String newVersion) {\n if (olderVerison.length() == 0 || newVersion.length() == 0) {\n return false;\n }\n List<String> newVerList = Arrays.asList(newVersion.split(\"\\\\.\"));\n List<String> oldVerList = Arrays.asList(olderVerison.split(\"\\\\.\"));\n\n int diff = newVerList.size() - oldVerList.size();\n List<String> newList = new ArrayList<>();\n if (diff > 0) {\n newList.addAll(oldVerList);\n for (int i = 0; i < diff; i++) {\n newList.add(\"0\");\n }\n return examineArray(newList, newVerList, diff);\n } else if (diff < 0) {\n newList.addAll(newVerList);\n for (int i = 0; i < -diff; i++) {\n newList.add(\"0\");\n }\n return examineArray(oldVerList, newList, diff);\n } else {\n return examineArray(oldVerList, newVerList, diff);\n }\n\n }\n\n public static boolean examineArray(List<String> oldList, List<String> newList, int diff) {\n boolean newVersionGreater = false;\n for (int i = 0; i < oldList.size(); i++) {\n if (Integer.parseInt(newList.get(i)) > Integer.parseInt(oldList.get(i))) {\n newVersionGreater = true;\n break;\n } else if (Integer.parseInt(newList.get(i)) < Integer.parseInt(oldList.get(i))) {\n newVersionGreater = false;\n break;\n } else {\n newVersionGreater = diff > 0;\n }\n }\n\n return newVersionGreater;\n }\n</code></pre>\n"
},
{
"answer_id": 50181582,
"author": "Stan Towianski",
"author_id": 2366973,
"author_profile": "https://Stackoverflow.com/users/2366973",
"pm_score": 2,
"selected": false,
"text": "<pre><code>/** \n * written by: Stan Towianski - May 2018 \n * notes: I make assumption each of 3 version sections a.b.c is not longer then 4 digits: aaaa.bbbb.cccc-MODWORD1(-)modnum2\n * 5.10.13-release-1 becomes 0000500100013.501 6.0-snapshot becomes 0000600000000.100\n * MODWORD1 = -xyz/NotMatching, -SNAPSHOT, -ALPHA, -BETA, -RC, -RELEASE/nothing return: .0, .1, .2, .3, .4, .5\n * modnum2 = up to 2 digit/chars second version\n * */\npublic class VersionCk {\n\n private static boolean isVersionHigher( String baseVersion, String testVersion )\n {\n System.out.println( \"versionToComparable( baseVersion ) =\" + versionToComparable( baseVersion ) );\n System.out.println( \"versionToComparable( testVersion ) =\" + versionToComparable( testVersion ) + \" is this higher ?\" );\n return versionToComparable( testVersion ).compareTo( versionToComparable( baseVersion ) ) > 0;\n }\n\n //---- not worrying about += for something so small\n private static String versionToComparable( String version )\n {\n// System.out.println(\"version - \" + version);\n String versionNum = version;\n int at = version.indexOf( '-' );\n if ( at >= 0 )\n versionNum = version.substring( 0, at );\n\n String[] numAr = versionNum.split( \"\\\\.\" );\n String versionFormatted = \"0\";\n for ( String tmp : numAr )\n {\n versionFormatted += String.format( \"%4s\", tmp ).replace(' ', '0');\n }\n while ( versionFormatted.length() < 12 ) // pad out to aaaa.bbbb.cccc\n {\n versionFormatted += \"0000\";\n }\n// System.out.println( \"converted min version =\" + versionFormatted + \"= : \" + versionNum );\n return versionFormatted + getVersionModifier( version, at );\n }\n\n //---- use order low to high: -xyz, -SNAPSHOT, -ALPHA, -BETA, -RC, -RELEASE/nothing returns: 0, 1, 2, 3, 4, 5\n private static String getVersionModifier( String version, int at )\n {\n// System.out.println(\"version - \" + version );\n String[] wordModsAr = { \"-SNAPSHOT\", \"-ALPHA\", \"-BETA\", \"-RC\", \"-RELEASE\" }; \n\n if ( at < 0 )\n return \".\" + wordModsAr.length + \"00\"; // make nothing = RELEASE level\n\n int i = 1;\n for ( String word : wordModsAr )\n {\n if ( ( at = version.toUpperCase().indexOf( word ) ) > 0 )\n return \".\" + i + getSecondVersionModifier( version.substring( at + word.length() ) );\n i++;\n }\n\n return \".000\";\n }\n\n //---- add 2 chars for any number after first modifier. -rc2 or -rc-2 returns 02\n private static String getSecondVersionModifier( String version )\n {\n System.out.println( \"second modifier =\" + version + \"=\" );\n Matcher m = Pattern.compile(\"(.*?)(\\\\d+).*\").matcher( version );\n// if ( m.matches() )\n// System.out.println( \"match ? =\" + m.matches() + \"= m.group(1) =\" + m.group(1) + \"= m.group(2) =\" + m.group(2) + \"= m.group(3) =\" + (m.groupCount() >= 3 ? m.group(3) : \"x\") );\n// else\n// System.out.println( \"No match\" );\n return m.matches() ? String.format( \"%2s\", m.group(2) ).replace(' ', '0') : \"00\";\n }\n\n public static void main(String[] args) \n {\n checkVersion( \"3.10.0\", \"3.4.0\");\n checkVersion( \"5.4.2\", \"5.4.1\");\n checkVersion( \"5.4.4\", \"5.4.5\");\n checkVersion( \"5.4.9\", \"5.4.12\");\n checkVersion( \"5.9.222\", \"5.10.12\");\n checkVersion( \"5.10.12\", \"5.10.12\");\n checkVersion( \"5.10.13\", \"5.10.14\");\n checkVersion( \"6.7.0\", \"6.8\");\n checkVersion( \"6.7\", \"2.7.0\");\n checkVersion( \"6\", \"6.3.1\");\n checkVersion( \"4\", \"4.0.0\");\n checkVersion( \"6.3.0\", \"6\");\n checkVersion( \"5.10.12-Alpha\", \"5.10.12-beTA\");\n checkVersion( \"5.10.13-release\", \"5.10.14-beta\");\n checkVersion( \"6.7.0\", \"6.8-snapshot\");\n checkVersion( \"6.7.1\", \"6.7.0-release\");\n checkVersion( \"6-snapshot\", \"6.0.0-beta\");\n checkVersion( \"6.0-snapshot\", \"6.0.0-whatthe\");\n checkVersion( \"5.10.12-Alpha-1\", \"5.10.12-alpha-2\");\n checkVersion( \"5.10.13-release-1\", \"5.10.13-release2\");\n checkVersion( \"10-rc42\", \"10.0.0-rc53\");\n }\n\n private static void checkVersion(String baseVersion, String testVersion) \n {\n System.out.println( \"baseVersion - \" + baseVersion );\n System.out.println( \"testVersion - \" + testVersion );\n System.out.println( \"isVersionHigher = \" + isVersionHigher( baseVersion, testVersion ) );\n System.out.println( \"---------------\");\n }\n\n }\n</code></pre>\n\n<p>some output:</p>\n\n<pre><code>---------------\nbaseVersion - 6.7\ntestVersion - 2.7.0\nversionToComparable( baseVersion ) =0000600070000.500\nversionToComparable( testVersion ) =0000200070000.500 is this higher ?\nisVersionHigher = false\n---------------\nbaseVersion - 6\ntestVersion - 6.3.1\nversionToComparable( baseVersion ) =0000600000000.500\nversionToComparable( testVersion ) =0000600030001.500 is this higher ?\nisVersionHigher = true\n---------------\nbaseVersion - 4\ntestVersion - 4.0.0\nversionToComparable( baseVersion ) =0000400000000.500\nversionToComparable( testVersion ) =0000400000000.500 is this higher ?\nisVersionHigher = false\n---------------\nbaseVersion - 6.3.0\ntestVersion - 6\nversionToComparable( baseVersion ) =0000600030000.500\nversionToComparable( testVersion ) =0000600000000.500 is this higher ?\nisVersionHigher = false\n---------------\nbaseVersion - 5.10.12-Alpha\ntestVersion - 5.10.12-beTA\nsecond modifier ==\nversionToComparable( baseVersion ) =0000500100012.200\nsecond modifier ==\nversionToComparable( testVersion ) =0000500100012.300 is this higher ?\nsecond modifier ==\nsecond modifier ==\nisVersionHigher = true\n---------------\nbaseVersion - 5.10.13-release\ntestVersion - 5.10.14-beta\nsecond modifier ==\nversionToComparable( baseVersion ) =0000500100013.500\nsecond modifier ==\nversionToComparable( testVersion ) =0000500100014.300 is this higher ?\nsecond modifier ==\nsecond modifier ==\nisVersionHigher = true\n---------------\nbaseVersion - 6.7.0\ntestVersion - 6.8-snapshot\nversionToComparable( baseVersion ) =0000600070000.500\nsecond modifier ==\nversionToComparable( testVersion ) =0000600080000.100 is this higher ?\nsecond modifier ==\nisVersionHigher = true\n---------------\nbaseVersion - 6.7.1\ntestVersion - 6.7.0-release\nversionToComparable( baseVersion ) =0000600070001.500\nsecond modifier ==\nversionToComparable( testVersion ) =0000600070000.500 is this higher ?\nsecond modifier ==\nisVersionHigher = false\n---------------\nbaseVersion - 6-snapshot\ntestVersion - 6.0.0-beta\nsecond modifier ==\nversionToComparable( baseVersion ) =0000600000000.100\nsecond modifier ==\nversionToComparable( testVersion ) =0000600000000.300 is this higher ?\nsecond modifier ==\nsecond modifier ==\nisVersionHigher = true\n---------------\nbaseVersion - 6.0-snapshot\ntestVersion - 6.0.0-whatthe\nsecond modifier ==\nversionToComparable( baseVersion ) =0000600000000.100\nversionToComparable( testVersion ) =0000600000000.000 is this higher ?\nsecond modifier ==\nisVersionHigher = false\n---------------\nbaseVersion - 5.10.12-Alpha-1\ntestVersion - 5.10.12-alpha-2\nsecond modifier =-1=\nversionToComparable( baseVersion ) =0000500100012.201\nsecond modifier =-2=\nversionToComparable( testVersion ) =0000500100012.202 is this higher ?\nsecond modifier =-2=\nsecond modifier =-1=\nisVersionHigher = true\n---------------\nbaseVersion - 5.10.13-release-1\ntestVersion - 5.10.13-release2\nsecond modifier =-1=\nversionToComparable( baseVersion ) =0000500100013.501\nsecond modifier =2=\nversionToComparable( testVersion ) =0000500100013.502 is this higher ?\nsecond modifier =2=\nsecond modifier =-1=\nisVersionHigher = true\n---------------\nbaseVersion - 10-rc42\ntestVersion - 10.0.0-rc53\nsecond modifier =42=\nversionToComparable( baseVersion ) =0001000000000.442\nsecond modifier =53=\nversionToComparable( testVersion ) =0001000000000.453 is this higher ?\nsecond modifier =53=\nsecond modifier =42=\nisVersionHigher = true\n---------------\n</code></pre>\n"
},
{
"answer_id": 53944480,
"author": "Maciej Dzikowicki",
"author_id": 3249355,
"author_profile": "https://Stackoverflow.com/users/3249355",
"pm_score": 3,
"selected": false,
"text": "<p>If you already have Jackson in your project, you can use <code>com.fasterxml.jackson.core.Version</code>:</p>\n\n<pre><code>import com.fasterxml.jackson.core.Version;\nimport org.junit.Test;\n\nimport static org.junit.Assert.assertTrue;\n\npublic class VersionTest {\n\n @Test\n public void shouldCompareVersion() {\n Version version1 = new Version(1, 11, 1, null, null, null);\n Version version2 = new Version(1, 12, 1, null, null, null);\n assertTrue(version1.compareTo(version2) < 0);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55023200,
"author": "Michael Gantman",
"author_id": 5802417,
"author_profile": "https://Stackoverflow.com/users/5802417",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote an Open Source Library called MgntUtils that has a utility that works with String versions. It correctly compares them, works with version ranges and so forth. Here is this library <a href=\"http://michaelgantman.github.io/Mgnt/docs/\" rel=\"nofollow noreferrer\">javadoc</a> See methods <code>TextUtils.comapreVersions(...)</code>. It has been heavily used and well tested. Here is the <a href=\"https://community.oracle.com/blogs/michaelgantman/2016/01/26/open-source-java-library-with-stacktrace-filtering-silent-string-parsing-and-version-comparison\" rel=\"nofollow noreferrer\">article</a> that describes the library and where to get it. It is available as <a href=\"https://search.maven.org/search?q=MgntUtils\" rel=\"nofollow noreferrer\">Maven artifact</a> and on the <a href=\"https://github.com/michaelgantman/Mgnt\" rel=\"nofollow noreferrer\">github</a> (with sources and JavaDoc)</p>\n"
},
{
"answer_id": 55141303,
"author": "ban",
"author_id": 4269728,
"author_profile": "https://Stackoverflow.com/users/4269728",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public int CompareVersions(String version1, String version2)\n{\n String[] string1Vals = version1.split(\"\\\\.\");\n String[] string2Vals = version2.split(\"\\\\.\");\n\n int length = Math.max(string1Vals.length, string2Vals.length);\n\n for (int i = 0; i < length; i++)\n {\n Integer v1 = (i < string1Vals.length)?Integer.parseInt(string1Vals[i]):0;\n Integer v2 = (i < string2Vals.length)?Integer.parseInt(string2Vals[i]):0;\n\n //Making sure Version1 bigger than version2\n if (v1 > v2)\n {\n return 1;\n }\n //Making sure Version1 smaller than version2\n else if(v1 < v2)\n {\n return -1;\n }\n }\n\n //Both are equal\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 57338571,
"author": "G00fY",
"author_id": 3660290,
"author_profile": "https://Stackoverflow.com/users/3660290",
"pm_score": 1,
"selected": false,
"text": "<p>I have written a small Java/Android library for comparing version numbers: <a href=\"https://github.com/G00fY2/version-compare\" rel=\"nofollow noreferrer\">https://github.com/G00fY2/version-compare</a></p>\n\n<p>What it basically does is this:</p>\n\n<pre><code> public int compareVersions(String versionA, String versionB) {\n String[] versionTokensA = versionA.split(\"\\\\.\");\n String[] versionTokensB = versionB.split(\"\\\\.\");\n List<Integer> versionNumbersA = new ArrayList<>();\n List<Integer> versionNumbersB = new ArrayList<>();\n\n for (String versionToken : versionTokensA) {\n versionNumbersA.add(Integer.parseInt(versionToken));\n }\n for (String versionToken : versionTokensB) {\n versionNumbersB.add(Integer.parseInt(versionToken));\n }\n\n final int versionASize = versionNumbersA.size();\n final int versionBSize = versionNumbersB.size();\n int maxSize = Math.max(versionASize, versionBSize);\n\n for (int i = 0; i < maxSize; i++) {\n if ((i < versionASize ? versionNumbersA.get(i) : 0) > (i < versionBSize ? versionNumbersB.get(i) : 0)) {\n return 1;\n } else if ((i < versionASize ? versionNumbersA.get(i) : 0) < (i < versionBSize ? versionNumbersB.get(i) : 0)) {\n return -1;\n }\n }\n return 0;\n }\n</code></pre>\n\n<p>This snippet doesn't offer any error checks or handling. Beside that my library also supports suffixes like \"1.2-rc\" > \"1.2-beta\".</p>\n"
},
{
"answer_id": 57900552,
"author": "Saurav Sahu",
"author_id": 1465553,
"author_profile": "https://Stackoverflow.com/users/1465553",
"pm_score": 0,
"selected": false,
"text": "<p>Using Java 8 Stream to replace leading zeroes in components. This code passed all tests on <a href=\"https://www.interviewbit.com/problems/compare-version-numbers/\" rel=\"nofollow noreferrer\">interviewbit.com</a></p>\n\n<pre><code>public int compareVersion(String A, String B) {\n List<String> strList1 = Arrays.stream(A.split(\"\\\\.\"))\n .map(s -> s.replaceAll(\"^0+(?!$)\", \"\"))\n .collect(Collectors.toList());\n List<String> strList2 = Arrays.stream(B.split(\"\\\\.\"))\n .map(s -> s.replaceAll(\"^0+(?!$)\", \"\"))\n .collect(Collectors.toList());\n int len1 = strList1.size();\n int len2 = strList2.size();\n int i = 0;\n while(i < len1 && i < len2){\n if (strList1.get(i).length() > strList2.get(i).length()) return 1;\n if (strList1.get(i).length() < strList2.get(i).length()) return -1;\n int result = new Long(strList1.get(i)).compareTo(new Long(strList2.get(i)));\n if (result != 0) return result;\n i++;\n }\n while (i < len1){\n if (!strList1.get(i++).equals(\"0\")) return 1;\n }\n while (i < len2){\n if (!strList2.get(i++).equals(\"0\")) return -1;\n }\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 58876745,
"author": "felixh",
"author_id": 3415235,
"author_profile": "https://Stackoverflow.com/users/3415235",
"pm_score": 1,
"selected": false,
"text": "<p>Since no answer on this page handles mixed text well, I made my own version:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nclass Main {\n static double parseVersion(String v) {\n if (v.isEmpty()) {\n return 0;\n }\n Pattern p = Pattern.compile("^(\\\\D*)(\\\\d*)(\\\\D*)$");\n Matcher m = p.matcher(v);\n m.find();\n if (m.group(2).isEmpty()) {\n // v1.0.0.[preview]\n return -1;\n }\n double i = Integer.parseInt(m.group(2));\n if (!m.group(3).isEmpty()) {\n // v1.0.[0b]\n i -= 0.1;\n }\n return i;\n }\n\n public static int versionCompare(String str1, String str2) {\n String[] v1 = str1.split("\\\\.");\n String[] v2 = str2.split("\\\\.");\n int i = 0;\n for (; i < v1.length && i < v2.length; i++) {\n double iv1 = parseVersion(v1[i]);\n double iv2 = parseVersion(v2[i]);\n\n if (iv1 != iv2) {\n return iv1 - iv2 < 0 ? -1 : 1;\n }\n }\n if (i < v1.length) {\n // "1.0.1", "1.0"\n double iv1 = parseVersion(v1[i]);\n return iv1 < 0 ? -1 : (int) Math.ceil(iv1);\n }\n if (i < v2.length) {\n double iv2 = parseVersion(v2[i]);\n return -iv2 < 0 ? -1 : (int) Math.ceil(iv2);\n }\n return 0;\n }\n\n\n public static void main(String[] args) {\n System.out.println("versionCompare(v1.0.0, 1.0.0)");\n System.out.println(versionCompare("v1.0.0", "1.0.0")); // 0\n\n System.out.println("versionCompare(v1.0.0b, 1.0.0)");\n System.out.println(versionCompare("v1.0.0b", "1.0.0")); // -1\n\n System.out.println("versionCompare(v1.0.0.preview, 1.0.0)");\n System.out.println(versionCompare("v1.0.0.preview", "1.0.0")); // -1\n\n System.out.println("versionCompare(v1.0, 1.0.0)");\n System.out.println(versionCompare("v1.0", "1.0.0")); // 0\n\n System.out.println("versionCompare(ver1.0, 1.0.1)");\n System.out.println(versionCompare("ver1.0", "1.0.1")); // -1\n }\n}\n</code></pre>\n<p>It still falls short on cases where you need to compare "alpha" with "beta" though.</p>\n"
},
{
"answer_id": 59214235,
"author": "BharathRao",
"author_id": 8331006,
"author_profile": "https://Stackoverflow.com/users/8331006",
"pm_score": 0,
"selected": false,
"text": "<p>For someone who is going to show Force Update Alert based on version number I have a following Idea. This may be used when comparing the versions between Android Current App version and firebase remote config version. This is not exactly the answer for the question asked but this will help someone definitely.</p>\n\n<pre><code>import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\npublic class Main\n{\n static String firebaseVersion = \"2.1.3\"; // or 2.1\n static String appVersion = \"2.1.4\";\n static List<String> firebaseVersionArray;\n static List<String> appVersionArray;\n static boolean isNeedToShowAlert = false;\n public static void main (String[]args)\n {\n System.out.println (\"Hello World\");\n firebaseVersionArray = new ArrayList<String>(Arrays.asList(firebaseVersion.split (\"\\\\.\")));\n appVersionArray = new ArrayList<String>(Arrays.asList(appVersion.split (\"\\\\.\")));\n if(appVersionArray.size() < firebaseVersionArray.size()) {\n appVersionArray.add(\"0\");\n }\n if(firebaseVersionArray.size() < appVersionArray.size()) {\n firebaseVersionArray.add(\"0\");\n }\n isNeedToShowAlert = needToShowAlert(); //Returns false\n System.out.println (isNeedToShowAlert);\n\n }\n static boolean needToShowAlert() {\n boolean result = false;\n for(int i = 0 ; i < appVersionArray.size() ; i++) {\n if (Integer.parseInt(appVersionArray.get(i)) == Integer.parseInt(firebaseVersionArray.get(i))) {\n continue;\n } else if (Integer.parseInt(appVersionArray.get(i)) > Integer.parseInt(firebaseVersionArray.get(i))){\n result = false;\n break;\n } else if (Integer.parseInt(appVersionArray.get(i)) < Integer.parseInt(firebaseVersionArray.get(i))) {\n result = true;\n break; \n }\n }\n return result;\n }\n}\n</code></pre>\n\n<p>You can run this code by copy pasting in \n<a href=\"https://www.onlinegdb.com/online_java_compiler\" rel=\"nofollow noreferrer\">https://www.onlinegdb.com/online_java_compiler</a></p>\n"
},
{
"answer_id": 59906510,
"author": "Lakshmi Narayana Galla",
"author_id": 7269334,
"author_profile": "https://Stackoverflow.com/users/7269334",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static void main(String[] args) {\n\n String version1 = \"1.0\";\n String version2 = \"1.0.0\";\n String[] version1_splits = version1.split(\"\\\\.\");\n String[] version2_splits = version2.split(\"\\\\.\");\n int length = version1_splits.length >= version2_splits.length ? version1_splits.length : version2_splits.length;\n int i=0;\n for(;i<length;i++){\n int version1_int = getValue(version1_splits,i);\n int version2_int = getValue(version2_splits,i);\n if(version1_int > version2_int){\n System.out.println(\"version1 > version2\");\n break;\n }\n else if(version1_int < version2_int){\n System.out.println(\"version2 > version1\");\n break;\n }\n else{\n if(i == length-1)\n System.out.println(\"version1 = version2\");\n }\n }\n}\n\nprivate static int getValue(String[] version1_splits, int i) {\n int temp;\n try{\n temp = Integer.valueOf(version1_splits[i]);\n }\n catch(IndexOutOfBoundsException e){\n temp=0;\n }\n\n return temp;\n}\n</code></pre>\n"
},
{
"answer_id": 61420225,
"author": "Marcello Câmara",
"author_id": 11157397,
"author_profile": "https://Stackoverflow.com/users/11157397",
"pm_score": 2,
"selected": false,
"text": "<p>I done it right now and asked myself, is it correct? Because I've never found a cleanest solution before than mine:</p>\n<p>You just need to split the string versions ("1.0.0") like this example:</p>\n<pre><code>userVersion.split("\\\\.")\n</code></pre>\n<p>Then you will have: {"1", "0", "0"}</p>\n<p>Now, using the method that I done:</p>\n<pre><code>isUpdateAvailable(userVersion.split("\\\\."), latestVersionSplit.split("\\\\."));\n</code></pre>\n<p>Method:</p>\n<pre><code>/**\n * Compare two versions\n *\n * @param userVersionSplit - User string array with major, minor and patch version from user (exemple: {"5", "2", "70"})\n * @param latestVersionSplit - Latest string array with major, minor and patch version from api (example: {"5", "2", "71"})\n * @return true if user version is smaller than latest version\n */\npublic static boolean isUpdateAvailable(String[] userVersionSplit, String[] latestVersionSplit) {\n\n try {\n int majorUserVersion = Integer.parseInt(userVersionSplit[0]);\n int minorUserVersion = Integer.parseInt(userVersionSplit[1]);\n int patchUserVersion = Integer.parseInt(userVersionSplit[2]);\n\n int majorLatestVersion = Integer.parseInt(latestVersionSplit[0]);\n int minorLatestVersion = Integer.parseInt(latestVersionSplit[1]);\n int patchLatestVersion = Integer.parseInt(latestVersionSplit[2]);\n\n if (majorUserVersion <= majorLatestVersion) {\n if (majorUserVersion < majorLatestVersion) {\n return true;\n } else {\n if (minorUserVersion <= minorLatestVersion) {\n if (minorUserVersion < minorLatestVersion) {\n return true;\n } else {\n return patchUserVersion < patchLatestVersion;\n }\n }\n }\n }\n } catch (Exception ignored) {\n // Will be throw only if the versions pattern is different from "x.x.x" format\n // Will return false at the end\n }\n\n return false;\n}\n</code></pre>\n<p>Waiting for any feedback :)</p>\n"
},
{
"answer_id": 61795721,
"author": "Serg Burlaka",
"author_id": 6352712,
"author_profile": "https://Stackoverflow.com/users/6352712",
"pm_score": 2,
"selected": false,
"text": "<p>@alex's <a href=\"https://stackoverflow.com/a/11024200/6352712\">post</a> on Kotlin</p>\n\n<pre><code>class Version(inputVersion: String) : Comparable<Version> {\n\n var version: String\n private set\n\n override fun compareTo(other: Version) =\n (split() to other.split()).let {(thisParts, thatParts)->\n val length = max(thisParts.size, thatParts.size)\n for (i in 0 until length) {\n val thisPart = if (i < thisParts.size) thisParts[i].toInt() else 0\n val thatPart = if (i < thatParts.size) thatParts[i].toInt() else 0\n if (thisPart < thatPart) return -1\n if (thisPart > thatPart) return 1\n }\n 0\n }\n\n init {\n require(inputVersion.matches(\"[0-9]+(\\\\.[0-9]+)*\".toRegex())) { \"Invalid version format\" }\n version = inputVersion\n }\n }\n\n fun Version.split() = version.split(\".\").toTypedArray()\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>Version(\"1.2.4\").compareTo(Version(\"0.0.5\")) //return 1\n</code></pre>\n"
},
{
"answer_id": 62532745,
"author": "Alessandro Scarozza",
"author_id": 2642478,
"author_profile": "https://Stackoverflow.com/users/2642478",
"pm_score": 1,
"selected": false,
"text": "<p>based on <a href=\"https://stackoverflow.com/a/27891752/2642478\">https://stackoverflow.com/a/27891752/2642478</a></p>\n<pre><code>class Version(private val value: String) : Comparable<Version> {\n private val splitted by lazy { value.split("-").first().split(".").map { it.toIntOrNull() ?: 0 } }\n\n override fun compareTo(other: Version): Int {\n for (i in 0 until maxOf(splitted.size, other.splitted.size)) {\n val compare = splitted.getOrElse(i) { 0 }.compareTo(other.splitted.getOrElse(i) { 0 })\n if (compare != 0)\n return compare\n }\n return 0\n }\n}\n</code></pre>\n<p>you can use like:</p>\n<pre><code> System.err.println(Version("1.0").compareTo( Version("1.0")))\n System.err.println(Version("1.0") < Version("1.1"))\n System.err.println(Version("1.10") > Version("1.9"))\n System.err.println(Version("1.10.1") > Version("1.10"))\n System.err.println(Version("0.0.1") < Version("1"))\n</code></pre>\n"
},
{
"answer_id": 64374606,
"author": "Artyom Deynega",
"author_id": 2787260,
"author_profile": "https://Stackoverflow.com/users/2787260",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe someone will be interested in my solution:</p>\n<pre><code>class Version private constructor(private val versionString: String) : Comparable<Version> {\n\n private val major: Int by lazy { versionString.split(".")[0].toInt() }\n\n private val minor: Int by lazy { versionString.split(".")[1].toInt() }\n\n private val patch: Int by lazy {\n val splitArray = versionString.split(".")\n\n if (splitArray.size == 3)\n splitArray[2].toInt()\n else\n 0\n }\n\n override fun compareTo(other: Version): Int {\n return when {\n major > other.major -> 1\n major < other.major -> -1\n minor > other.minor -> 1\n minor < other.minor -> -1\n patch > other.patch -> 1\n patch < other.patch -> -1\n else -> 0\n }\n }\n\n override fun equals(other: Any?): Boolean {\n if (other == null || other !is Version) return false\n return compareTo(other) == 0\n }\n\n override fun hashCode(): Int {\n return major * minor * patch\n }\n\n companion object {\n private fun doesContainsVersion(string: String): Boolean {\n val versionArray = string.split(".")\n\n return versionArray.size in 2..3\n && versionArray[0].toIntOrNull() != null\n && versionArray[1].toIntOrNull() != null\n && (versionArray.size == 2 || versionArray[2].toIntOrNull() != null)\n }\n\n fun from(string: String): Version? {\n return if (doesContainsVersion(string)) {\n Version(string)\n } else {\n null\n }\n }\n }\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>val version1 = Version.from("3.2")\nval version2 = Version.from("3.2.1")\nversion1 <= version2\n\n</code></pre>\n"
},
{
"answer_id": 65077344,
"author": "Olivier Grégoire",
"author_id": 180719,
"author_profile": "https://Stackoverflow.com/users/180719",
"pm_score": 6,
"selected": false,
"text": "<h1>Use Java 9's <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/module/ModuleDescriptor.Version.html\" rel=\"noreferrer\">own builtin <code>Version</code> class</a></h1>\n<pre><code>import java.util.*;\nimport java.lang.module.ModuleDescriptor.Version;\nclass Main {\n public static void main(String[] args) {\n var versions = Arrays.asList(\n "1.0.2",\n "1.0.0-beta.2",\n "1.0.0",\n "1.0.0-beta",\n "1.0.0-alpha.12",\n "1.0.0-beta.11",\n "1.0.1",\n "1.0.11",\n "1.0.0-rc.1",\n "1.0.0-alpha.1",\n "1.1.0",\n "1.0.0-alpha.beta",\n "1.11.0",\n "1.0.0-alpha.12.ab-c",\n "0.0.1",\n "1.2.1",\n "1.0.0-alpha",\n "1.0.0.1", // Also works with a number of sections different than 3\n "1.0.0.2",\n "2",\n "10",\n "1.0.0.10"\n );\n versions.stream()\n .map(Version::parse)\n .sorted()\n .forEach(System.out::println);\n }\n}\n</code></pre>\n<p><a href=\"https://tio.run/##dZI9b8JADIb3/AqLKVTlyNEN1AGp3cqE1KXq4CQXcnC5i@xLEKr47WkaUAkBJsuvH3/I9hZrnGzTXdPoonTkYdsKovLaiKdF0NcM2o0oXFoZJVadeVOckC69I/GpiLWziyAxyAwr1BZ@AoCyio1OgD361tROp1C0sXDtSdvN1zcgbXjcoQA1EtSnQgyvsCTCAwvkD80@7AiAkRSRmI2e@240iZXHG/UeNNTQlDkKeb@glNfy0JXDLEqEfNChL8vb2U7UcEL5kJQzgfEkuQSj4XyzB6MMxD8KYDqFpWEHe0c7hr32OSDYqogVgcuAVeK7o6Q6yxQp68HnaOHlulRvi/2FRjcto1EnjBens59PLtiTwiIcn2lRYBmeH2s@L5FY/Ye4fUuVXtDM0Tsmebg@sFeFcJVvM9oX88Z2XY7BsWl@AQ\" rel=\"noreferrer\" title=\"Java (JDK) – Try It Online\">Try it online!</a></p>\n<p>Output:</p>\n<pre class=\"lang-text prettyprint-override\"><code>0.0.1\n1.0.0-alpha\n1.0.0-alpha.1\n1.0.0-alpha.12\n1.0.0-alpha.12.ab-c\n1.0.0-alpha.beta\n1.0.0-beta\n1.0.0-beta.2\n1.0.0-beta.11\n1.0.0-rc.1\n1.0.0\n1.0.0.1\n1.0.0.2\n1.0.0.10\n1.0.1\n1.0.2\n1.0.11\n1.1.0\n1.2.1\n1.11.0\n2\n10\n</code></pre>\n"
},
{
"answer_id": 71320022,
"author": "legendmohe",
"author_id": 1349479,
"author_profile": "https://Stackoverflow.com/users/1349479",
"pm_score": 0,
"selected": false,
"text": "<p>kotlin:</p>\n<pre><code>@kotlin.jvm.Throws(InvalidParameterException::class)\nfun String.versionCompare(remoteVersion: String?): Int {\n val remote = remoteVersion?.splitToSequence(".")?.toList() ?: return 1\n val local = this.splitToSequence(".").toList()\n\n if(local.filter { it.toIntOrNull() != null }.size != local.size) throw InvalidParameterException("version invalid: $this")\n if(remote.filter { it.toIntOrNull() != null }.size != remote.size) throw InvalidParameterException("version invalid: $remoteVersion")\n\n val totalRange = 0 until kotlin.math.max(local.size, remote.size)\n for (i in totalRange) {\n if (i < remote.size && i < local.size) {\n val result = local[i].compareTo(remote[i])\n if (result != 0) return result\n } else (\n return local.size.compareTo(remote.size)\n )\n }\n return 0\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
Is there a standard idiom for comparing version numbers? I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be. I need to compare the versions and have the following hold true:
```
1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
```
|
Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.
|
198,460 |
<p>How do I generate a random number between <code>0</code> and <code>n</code>?</p>
|
[
{
"answer_id": 198469,
"author": "Mark A. Nicolosi",
"author_id": 1103052,
"author_profile": "https://Stackoverflow.com/users/1103052",
"pm_score": 5,
"selected": false,
"text": "<p>Well, I figured it out. Apparently there is a builtin (?) function called rand:</p>\n\n<pre><code>rand(n + 1)\n</code></pre>\n\n<p>If someone answers with a more detailed answer, I'll mark that as the correct answer.</p>\n"
},
{
"answer_id": 198470,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 11,
"selected": true,
"text": "<p>Use <a href=\"http://www.ruby-doc.org/core-2.1.3/Kernel.html#method-i-rand\" rel=\"noreferrer\"><code>rand(range)</code></a></p>\n\n<p>From <a href=\"http://www.codeodor.com/index.cfm/2007/3/25/Ruby-random-numbers/1042\" rel=\"noreferrer\">Ruby Random Numbers</a>:</p>\n\n<blockquote>\n <p>If you needed a random integer to simulate a roll of a six-sided die, you'd use: <code>1 + rand(6)</code>. A roll in craps could be simulated with <code>2 + rand(6) + rand(6)</code>.</p>\n \n <p>Finally, if you just need a random float, just call <code>rand</code> with no arguments.</p>\n</blockquote>\n\n<hr>\n\n<p>As <a href=\"https://stackoverflow.com/users/8279/marc-andre-lafortune\">Marc-André Lafortune</a> mentions in <a href=\"https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866\">his answer below (go upvote it)</a>, <a href=\"http://www.ruby-lang.org/en/news/2009/07/20/ruby-1-9-2-preview-1-released/\" rel=\"noreferrer\">Ruby 1.9.2 has its own <code>Random</code> class</a> (that Marc-André himself <a href=\"http://redmine.ruby-lang.org/issues/show/3104\" rel=\"noreferrer\">helped to debug</a>, hence the <a href=\"http://redmine.ruby-lang.org/versions/show/11\" rel=\"noreferrer\">1.9.2 target</a> for that feature).</p>\n\n<p>For instance, in this <a href=\"http://www.eggheadcafe.com/software/aspnet/35817496/random-integer-within-a-r.aspx\" rel=\"noreferrer\">game where you need to guess 10 numbers</a>, you can initialize them with:</p>\n\n<pre><code>10.times.map{ 20 + Random.rand(11) } \n#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]\n</code></pre>\n\n<p>Note: </p>\n\n<ul>\n<li><p>Using <code>Random.new.rand(20..30)</code> (using <code>Random.new</code>) generally would not be a good idea, as explained in detail (again) by <a href=\"https://stackoverflow.com/users/8279/marc-andre-lafortune\">Marc-André Lafortune</a>, in <a href=\"https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866\">his answer</a> (again).</p></li>\n<li><p>But if you don't use <code>Random.new</code>, then the <a href=\"http://www.ruby-doc.org/core/classes/Random.src/M000693.html\" rel=\"noreferrer\">class method <code>rand</code></a> only takes a <code>max</code> value, not a <code>Range</code>, as <a href=\"https://stackoverflow.com/users/66725/banister\">banister</a> (energetically) points out in the comment (and as documented in the <a href=\"http://www.ruby-doc.org/core/classes/Random.html\" rel=\"noreferrer\">docs for <code>Random</code></a>). Only the <a href=\"http://www.ruby-doc.org/core/classes/Random.src/M000688.html\" rel=\"noreferrer\">instance method</a> can take a <code>Range</code>, as illustrated by <a href=\"https://stackoverflow.com/questions/5722881/generate-a-random-number-with-7-digits/5723105#5723105\">generate a random number with 7 digits</a>.</p></li>\n</ul>\n\n<p>This is why the equivalent of <code>Random.new.rand(20..30)</code> would be <code>20 + Random.rand(11)</code>, since <code>Random.rand(int)</code> returns “a random integer greater than or equal to zero and <em>less than the argument</em>.” <code>20..30</code> includes 30, I need to come up with a random number between 0 and 11, excluding 11.</p>\n"
},
{
"answer_id": 198486,
"author": "Liebach",
"author_id": 27554,
"author_profile": "https://Stackoverflow.com/users/27554",
"pm_score": 1,
"selected": false,
"text": "<p>Don't forget to seed the RNG with <em>srand()</em> first.</p>\n"
},
{
"answer_id": 2773866,
"author": "Marc-André Lafortune",
"author_id": 8279,
"author_profile": "https://Stackoverflow.com/users/8279",
"pm_score": 9,
"selected": false,
"text": "<p>While you can use <code>rand(42-10) + 10</code> to get a random number between <code>10</code> and <code>42</code> (where 10 is inclusive and 42 exclusive), there's a better way since Ruby 1.9.3, where you are able to call:</p>\n\n<pre><code>rand(10...42) # => 13\n</code></pre>\n\n<p>Available for all versions of Ruby by requiring my <a href=\"http://github.com/marcandre/backports\" rel=\"noreferrer\"><code>backports</code></a> gem.</p>\n\n<p>Ruby 1.9.2 also introduced the <code>Random</code> class so you can create your own random number generator objects and has a nice API:</p>\n\n<pre><code>r = Random.new\nr.rand(10...42) # => 22\nr.bytes(3) # => \"rnd\"\n</code></pre>\n\n<p>The <code>Random</code> class itself acts as a random generator, so you call directly:</p>\n\n<pre><code>Random.rand(10...42) # => same as rand(10...42)\n</code></pre>\n\n<p><strong><em>Notes on <code>Random.new</code></em></strong></p>\n\n<p>In most cases, the simplest is to use <code>rand</code> or <code>Random.rand</code>. Creating a new random generator each time you want a random number is a <em>really bad idea</em>. If you do this, you will get the random properties of the initial seeding algorithm which are atrocious compared to the properties of the <a href=\"http://en.wikipedia.org/wiki/Mersenne_twister\" rel=\"noreferrer\">random generator itself</a>.</p>\n\n<p>If you use <code>Random.new</code>, you should thus call it <em>as rarely as possible</em>, for example once as <code>MyApp::Random = Random.new</code> and use it everywhere else.</p>\n\n<p>The cases where <code>Random.new</code> is helpful are the following:</p>\n\n<ul>\n<li>you are writing a gem and don't want to interfere with the sequence of <code>rand</code>/<code>Random.rand</code> that the main programs might be relying on</li>\n<li>you want separate reproducible sequences of random numbers (say one per thread)</li>\n<li>you want to be able to save and resume a reproducible sequence of random numbers (easy as <code>Random</code> objects can marshalled)</li>\n</ul>\n"
},
{
"answer_id": 10714301,
"author": "Rimian",
"author_id": 63810,
"author_profile": "https://Stackoverflow.com/users/63810",
"pm_score": 4,
"selected": false,
"text": "<p>What about this?</p>\n\n<pre><code>n = 3\n(0..n).to_a.sample\n</code></pre>\n"
},
{
"answer_id": 11578224,
"author": "Thomas Fankhauser",
"author_id": 408557,
"author_profile": "https://Stackoverflow.com/users/408557",
"pm_score": 6,
"selected": false,
"text": "<p>If you're not only seeking for a number but also hex or uuid it's worth mentioning that the <code>SecureRandom</code> module found its way from <code>ActiveSupport</code> to the ruby core in 1.9.2+. So without the need for a full blown framework:</p>\n\n<pre><code>require 'securerandom'\n\np SecureRandom.random_number(100) #=> 15\np SecureRandom.random_number(100) #=> 88\n\np SecureRandom.random_number #=> 0.596506046187744\np SecureRandom.random_number #=> 0.350621695741409\n\np SecureRandom.hex #=> \"eb693ec8252cd630102fd0d0fb7c3485\"\n</code></pre>\n\n<p>It's documented here: <a href=\"http://rubydoc.info/stdlib/securerandom/1.9.3/SecureRandom\" rel=\"noreferrer\">Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb) </a></p>\n"
},
{
"answer_id": 13408086,
"author": "Josh",
"author_id": 1193216,
"author_profile": "https://Stackoverflow.com/users/1193216",
"pm_score": 3,
"selected": false,
"text": "<pre><code>rand(6) #=> gives a random number between 0 and 6 inclusively \nrand(1..6) #=> gives a random number between 1 and 6 inclusively\n</code></pre>\n\n<p>Note that the range option is only available in newer(1.9+ I believe) versions of ruby.</p>\n"
},
{
"answer_id": 13847818,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>You can generate a random number with the <code>rand</code> method. The argument passed to the <code>rand</code> method should be an <code>integer</code> or a <code>range</code>, and returns a corresponding random number within the range:</p>\n\n<pre><code>rand(9) # this generates a number between 0 to 8\nrand(0 .. 9) # this generates a number between 0 to 9\nrand(1 .. 50) # this generates a number between 1 to 50\n#rand(m .. n) # m is the start of the number range, n is the end of number range\n</code></pre>\n"
},
{
"answer_id": 20764761,
"author": "Sam",
"author_id": 1776255,
"author_profile": "https://Stackoverflow.com/users/1776255",
"pm_score": 2,
"selected": false,
"text": "<p>This link is going to be helpful regarding this;</p>\n\n<p><a href=\"http://ruby-doc.org/core-1.9.3/Random.html\" rel=\"nofollow\">http://ruby-doc.org/core-1.9.3/Random.html</a></p>\n\n<p><strong>And some more clarity below over the random numbers in ruby;</strong></p>\n\n<p>Generate an integer from 0 to 10</p>\n\n<pre><code>puts (rand() * 10).to_i\n</code></pre>\n\n<p>Generate a number from 0 to 10\nIn a more readable way</p>\n\n<pre><code>puts rand(10)\n</code></pre>\n\n<p>Generate a number from 10 to 15\nIncluding 15</p>\n\n<pre><code>puts rand(10..15)\n</code></pre>\n\n<p><strong>Non-Random Random Numbers</strong></p>\n\n<p>Generate the same sequence of numbers every time\nthe program is run</p>\n\n<pre><code>srand(5)\n</code></pre>\n\n<p>Generate 10 random numbers</p>\n\n<pre><code>puts (0..10).map{rand(0..10)}\n</code></pre>\n"
},
{
"answer_id": 28115646,
"author": "LuckyElf",
"author_id": 4479264,
"author_profile": "https://Stackoverflow.com/users/4479264",
"pm_score": 1,
"selected": false,
"text": "<p>Try <code>array#shuffle</code> method for randomization</p>\n\n<pre><code>array = (1..10).to_a\narray.shuffle.first\n</code></pre>\n"
},
{
"answer_id": 28614573,
"author": "sqrcompass",
"author_id": 3128333,
"author_profile": "https://Stackoverflow.com/users/3128333",
"pm_score": 4,
"selected": false,
"text": "<p>Simplest answer to the question:</p>\n\n<pre><code>rand(0..n)\n</code></pre>\n"
},
{
"answer_id": 32161641,
"author": "Scott",
"author_id": 3335551,
"author_profile": "https://Stackoverflow.com/users/3335551",
"pm_score": 3,
"selected": false,
"text": "<p>you can do rand(range)</p>\n\n<pre><code>x = rand(1..5)\n</code></pre>\n"
},
{
"answer_id": 35942168,
"author": "amarradi",
"author_id": 1200840,
"author_profile": "https://Stackoverflow.com/users/1200840",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe it help you. I use this in my app</p>\n\n<pre><code>https://github.com/rubyworks/facets\nclass String\n\n # Create a random String of given length, using given character set\n #\n # Character set is an Array which can contain Ranges, Arrays, Characters\n #\n # Examples\n #\n # String.random\n # => \"D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3\"\n #\n # String.random(10)\n # => \"t8BIna341S\"\n #\n # String.random(10, ['a'..'z'])\n # => \"nstpvixfri\"\n #\n # String.random(10, ['0'..'9'] )\n # => \"0982541042\"\n #\n # String.random(10, ['0'..'9','A'..'F'] )\n # => \"3EBF48AD3D\"\n #\n # BASE64_CHAR_SET = [\"A\"..\"Z\", \"a\"..\"z\", \"0\"..\"9\", '_', '-']\n # String.random(10, BASE64_CHAR_SET)\n # => \"xM_1t3qcNn\"\n #\n # SPECIAL_CHARS = [\"!\", \"@\", \"#\", \"$\", \"%\", \"^\", \"&\", \"*\", \"(\", \")\", \"-\", \"_\", \"=\", \"+\", \"|\", \"/\", \"?\", \".\", \",\", \";\", \":\", \"~\", \"`\", \"[\", \"]\", \"{\", \"}\", \"<\", \">\"]\n # BASE91_CHAR_SET = [\"A\"..\"Z\", \"a\"..\"z\", \"0\"..\"9\", SPECIAL_CHARS]\n # String.random(10, BASE91_CHAR_SET)\n # => \"S(Z]z,J{v;\"\n #\n # CREDIT: Tilo Sloboda\n #\n # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba\n #\n # TODO: Move to random.rb in standard library?\n\n def self.random(len=32, character_set = [\"A\"..\"Z\", \"a\"..\"z\", \"0\"..\"9\"])\n chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten\n Array.new(len){ chars.sample }.join\n end\n\nend\n</code></pre>\n\n<p><a href=\"https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb\" rel=\"nofollow\">https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb</a></p>\n\n<p>It works fine for me</p>\n"
},
{
"answer_id": 35942797,
"author": "Juan Dela Cruz",
"author_id": 4423225,
"author_profile": "https://Stackoverflow.com/users/4423225",
"pm_score": 2,
"selected": false,
"text": "<p>How about this one?</p>\n\n<pre><code>num = Random.new\nnum.rand(1..n)\n</code></pre>\n"
},
{
"answer_id": 36936006,
"author": "sumit",
"author_id": 5881210,
"author_profile": "https://Stackoverflow.com/users/5881210",
"pm_score": 3,
"selected": false,
"text": "<p>range = 10..50</p>\n\n<p><strong>rand(range)</strong></p>\n\n<p>or</p>\n\n<p><strong>range.to_a.sample</strong></p>\n\n<p>or</p>\n\n<p><strong>range.to_a.shuffle</strong>(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)</p>\n"
},
{
"answer_id": 41675944,
"author": "techdreams",
"author_id": 2936491,
"author_profile": "https://Stackoverflow.com/users/2936491",
"pm_score": 4,
"selected": false,
"text": "<p>You can simply use <code>random_number</code>.</p>\n\n<p>If a positive integer is given as n, <code>random_number</code> returns an integer: 0 <= <code>random_number</code> < n.</p>\n\n<p>Use it like this:</p>\n\n<pre><code>any_number = SecureRandom.random_number(100) \n</code></pre>\n\n<p>The output will be any number between 0 and 100.</p>\n"
},
{
"answer_id": 42270685,
"author": "Vaisakh VM",
"author_id": 1905008,
"author_profile": "https://Stackoverflow.com/users/1905008",
"pm_score": 2,
"selected": false,
"text": "<p>Easy way to get random number in ruby is,</p>\n\n<pre><code>def random \n (1..10).to_a.sample.to_s\nend\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103052/"
] |
How do I generate a random number between `0` and `n`?
|
Use [`rand(range)`](http://www.ruby-doc.org/core-2.1.3/Kernel.html#method-i-rand)
From [Ruby Random Numbers](http://www.codeodor.com/index.cfm/2007/3/25/Ruby-random-numbers/1042):
>
> If you needed a random integer to simulate a roll of a six-sided die, you'd use: `1 + rand(6)`. A roll in craps could be simulated with `2 + rand(6) + rand(6)`.
>
>
> Finally, if you just need a random float, just call `rand` with no arguments.
>
>
>
---
As [Marc-André Lafortune](https://stackoverflow.com/users/8279/marc-andre-lafortune) mentions in [his answer below (go upvote it)](https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866), [Ruby 1.9.2 has its own `Random` class](http://www.ruby-lang.org/en/news/2009/07/20/ruby-1-9-2-preview-1-released/) (that Marc-André himself [helped to debug](http://redmine.ruby-lang.org/issues/show/3104), hence the [1.9.2 target](http://redmine.ruby-lang.org/versions/show/11) for that feature).
For instance, in this [game where you need to guess 10 numbers](http://www.eggheadcafe.com/software/aspnet/35817496/random-integer-within-a-r.aspx), you can initialize them with:
```
10.times.map{ 20 + Random.rand(11) }
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]
```
Note:
* Using `Random.new.rand(20..30)` (using `Random.new`) generally would not be a good idea, as explained in detail (again) by [Marc-André Lafortune](https://stackoverflow.com/users/8279/marc-andre-lafortune), in [his answer](https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866) (again).
* But if you don't use `Random.new`, then the [class method `rand`](http://www.ruby-doc.org/core/classes/Random.src/M000693.html) only takes a `max` value, not a `Range`, as [banister](https://stackoverflow.com/users/66725/banister) (energetically) points out in the comment (and as documented in the [docs for `Random`](http://www.ruby-doc.org/core/classes/Random.html)). Only the [instance method](http://www.ruby-doc.org/core/classes/Random.src/M000688.html) can take a `Range`, as illustrated by [generate a random number with 7 digits](https://stackoverflow.com/questions/5722881/generate-a-random-number-with-7-digits/5723105#5723105).
This is why the equivalent of `Random.new.rand(20..30)` would be `20 + Random.rand(11)`, since `Random.rand(int)` returns “a random integer greater than or equal to zero and *less than the argument*.” `20..30` includes 30, I need to come up with a random number between 0 and 11, excluding 11.
|
198,465 |
<p>Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated? I openned up the csv module, and it appears it's contest are builtin. I also tried setting the file object as a property but I get the following error:</p>
<pre><code>AttributeError: '_csv.writer' object has no attribute 'fileobj'
</code></pre>
|
[
{
"answer_id": 198553,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": true,
"text": "<p><code>csv.writer</code> is a \"builtin\" function. That is, it is written in compiled C code rather than Python. So its internal variables can't be accessed from Python code.</p>\n\n<p>That being said, I'm not sure <strong>why</strong> you would need to inspect the csv.writer object to find out the file object. That object is specified when creating the object:</p>\n\n<pre><code>w = csv.writer(fileobj, dialect, ...)\n</code></pre>\n\n<p>So if you need to access that object later, just save it in another variable.</p>\n"
},
{
"answer_id": 3243629,
"author": "B N",
"author_id": 391224,
"author_profile": "https://Stackoverflow.com/users/391224",
"pm_score": 0,
"selected": false,
"text": "<p>From what I can tell, there is no straightforward way to get the file object back out once you put it into a csv object. My approach would probably be to subclass the csv writer and readers you're using so they can carry that data around with them. Of course, this assumes the ability to be able to directly access the types of classes the factory function makes (among other things).</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated? I openned up the csv module, and it appears it's contest are builtin. I also tried setting the file object as a property but I get the following error:
```
AttributeError: '_csv.writer' object has no attribute 'fileobj'
```
|
`csv.writer` is a "builtin" function. That is, it is written in compiled C code rather than Python. So its internal variables can't be accessed from Python code.
That being said, I'm not sure **why** you would need to inspect the csv.writer object to find out the file object. That object is specified when creating the object:
```
w = csv.writer(fileobj, dialect, ...)
```
So if you need to access that object later, just save it in another variable.
|
198,493 |
<p>I'm developing a system that needs to execute Intersystems Cache Terminal Scripts.</p>
<p>When I run a routine inside the regular Caché terminal or a telnet terminal, Cache executes the routine until the end with no problems. But when I try to run the same routine, but this time calling the routine within a Caché terminal Script, Caché disconnects the session after a while. There is no mention at all in the documentation of a "timeout" setting or anything realted to the "" messages i'm getting.</p>
<p>The script is run just like this:</p>
<pre><code>Cterm.exe /console=cn_iptcp:192.168.2.13[23] c:\test.s
</code></pre>
<p>1) Does anybody know what may be causing Interystems Caché to disconnected the session in the middle of the run (the session isn't idle either. It regularly outputs status messages to the console)?</p>
<p>2) Any ideas of how to solve it?</p>
<p>Thanks,</p>
<p>Luís Fernando</p>
|
[
{
"answer_id": 198655,
"author": "Clayton",
"author_id": 22201,
"author_profile": "https://Stackoverflow.com/users/22201",
"pm_score": 1,
"selected": false,
"text": "<p>Is there a chance it's not a timeout, but some other problem? Possibly a runtime error that's not being trapped/logged?</p>\n\n<p>The main difference between running from the interactive console and as a script is that when you run interactively you're in Programmer Mode, but in the script you're in User Mode. I can't think of any reason off-hand why that would matter, but possibly your code is sensitive to that.</p>\n\n<p>Here's something to try: Write a very simple script that does nothing except write out a character every now and then. Maybe something like this:</p>\n\n<p>F I=1:1:360 H 10 W \".\" ;Write a dot every 10 seconds for 1 hour</p>\n\n<p>If that gets the timeout too then you know it's the terminal, not your code.</p>\n"
},
{
"answer_id": 302330,
"author": "Luis Soeiro",
"author_id": 24165,
"author_profile": "https://Stackoverflow.com/users/24165",
"pm_score": 2,
"selected": false,
"text": "<p>After a while I finally discovered why the session was being terminated. You must wait for something at the end or the script just terminates. But you must be sure that the string you are waiting for is not something that will be printed until the code finishes.</p>\n\n<p>So, I've just changed the program to print \"Operation finished\" only at the end, and then put the line:</p>\n\n<pre><code> waitfor \"Operation finished\"\nterminate\n</code></pre>\n\n<p>Now the program doesn't get interrupted.</p>\n\n<p>Cheers,</p>\n\n<p>Luís</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24165/"
] |
I'm developing a system that needs to execute Intersystems Cache Terminal Scripts.
When I run a routine inside the regular Caché terminal or a telnet terminal, Cache executes the routine until the end with no problems. But when I try to run the same routine, but this time calling the routine within a Caché terminal Script, Caché disconnects the session after a while. There is no mention at all in the documentation of a "timeout" setting or anything realted to the "" messages i'm getting.
The script is run just like this:
```
Cterm.exe /console=cn_iptcp:192.168.2.13[23] c:\test.s
```
1) Does anybody know what may be causing Interystems Caché to disconnected the session in the middle of the run (the session isn't idle either. It regularly outputs status messages to the console)?
2) Any ideas of how to solve it?
Thanks,
Luís Fernando
|
After a while I finally discovered why the session was being terminated. You must wait for something at the end or the script just terminates. But you must be sure that the string you are waiting for is not something that will be printed until the code finishes.
So, I've just changed the program to print "Operation finished" only at the end, and then put the line:
```
waitfor "Operation finished"
terminate
```
Now the program doesn't get interrupted.
Cheers,
Luís
|
198,496 |
<p>What’s the difference between the <code>System.Array.CopyTo()</code> and <code>System.Array.Clone()</code>?</p>
|
[
{
"answer_id": 198500,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 7,
"selected": true,
"text": "<p>The <strong><a href=\"http://msdn.microsoft.com/en-us/library/system.array.clone.aspx\" rel=\"noreferrer\">Clone()</a></strong> method returns a new array (a shallow copy) object containing all the elements in the original array. The <strong><a href=\"http://msdn.microsoft.com/en-us/library/system.array.copyto.aspx\" rel=\"noreferrer\">CopyTo()</a></strong> method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.</p>\n\n<p>So the difference are :</p>\n\n<pre><code>1- CopyTo require to have a destination array when Clone return a new array.\n2- CopyTo let you specify an index (if required) to the destination array.\n</code></pre>\n\nEdit:\n\n<p>Remove the wrong example.</p>\n"
},
{
"answer_id": 198512,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "<p>Both perform shallow copies as @PatrickDesjardins said (despite the many misled souls who think that <code>CopyTo</code> does a deep copy).</p>\n\n<p>However, <code>CopyTo</code> allows you to copy one array to a specified index in the destination array, giving it significantly more flexibility.</p>\n"
},
{
"answer_id": 198602,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "<p>One other difference not mentioned so far is that</p>\n\n<ul>\n<li>with <code>Clone()</code> the destination array need not exist yet since a new one is created from scratch.</li>\n<li>with <code>CopyTo()</code> not only does the destination array need to already exist, it needs to be large enough to hold all the elements in the source array from the index you specify as the destination.</li>\n</ul>\n"
},
{
"answer_id": 1690062,
"author": "GenZiy",
"author_id": 201889,
"author_profile": "https://Stackoverflow.com/users/201889",
"pm_score": 3,
"selected": false,
"text": "<pre><code>object[] myarray = new object[] { \"one\", 2, \"three\", 4, \"really big number\", 2324573984927361 };\n\n//create shallow copy by CopyTo\n//You have to instantiate your new array first\nobject[] myarray2 = new object[myarray.Length];\n//but then you can specify how many members of original array you would like to copy \nmyarray.CopyTo(myarray2, 0);\n\n//create shallow copy by Clone\nobject[] myarray1;\n//here you don't need to instantiate array, \n//but all elements of the original array will be copied\nmyarray1 = myarray.Clone() as object[];\n\n//if not sure that we create a shalow copy lets test it\nmyarray[0] = 0;\nConsole.WriteLine(myarray[0]);// print 0\nConsole.WriteLine(myarray1[0]);//print \"one\"\nConsole.WriteLine(myarray2[0]);//print \"one\"\n</code></pre>\n\n<p><a href=\"http://mgznet.com/CopyToVSClone.aspx\" rel=\"noreferrer\">the source</a></p>\n"
},
{
"answer_id": 2123176,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p><code>Clone()</code> is used to copy only structure of data/array it doesn't copy the actual data.</p>\n\n<p><code>CopyTo()</code> copies the structure as well as actual data.</p>\n"
},
{
"answer_id": 5295876,
"author": "SFD",
"author_id": 642684,
"author_profile": "https://Stackoverflow.com/users/642684",
"pm_score": 2,
"selected": false,
"text": "<p>Both CopyTo() and Clone() make shallow copy. Clone() method makes a clone of the original array. It returns an exact length array.</p>\n\n<p>On the other hand, CopyTo() copies the elements from the original array to the destination array starting at the specified destination array index. Note that, this adds elements to an already existing array.</p>\n\n<p>The following code will contradict the postings saying that CopyTo() makes a deep copy:</p>\n\n<pre><code>public class Test\n{\npublic string s;\n}\n\n// Write Main() method and within it call test()\n\nprivate void test()\n{\nTest[] array = new Test[1];\narray[0] = new Test();\narray[0].s = \"ORIGINAL\";\n\nTest[] copy = new Test[1];\narray.CopyTo(copy, 0);\n\n// Next line displays \"ORIGINAL\"\nMessageBox.Show(\"array[0].s = \" + array[0].s);\ncopy[0].s = \"CHANGED\";\n\n// Next line displays \"CHANGED\", showing that\n// changing the copy also changes the original.\nMessageBox.Show(\"array[0].s = \" + array[0].s);\n}\n</code></pre>\n\n<p>Let me explain it a bit. If the elements of the array are of reference types, then the copy (both for Clone() and CopyTo()) will be made upto the first(top) level. But the lower level doesn't get copied. If we need copy of lower level also, we have to do it explicitly. That's why after Cloning or Copying of reference type elements, each element in the Cloned or Copied array refers to the same memory location as referred by the corresponding element in the original array. This clearly indicates that no separate instance is created for lower level. And if it were so then changing the value of any element in the Copied or Cloned array would not have effect in the corresponding element of the original array.</p>\n\n<p>I think that my explanation is exhaustive but I found no other way to make it understandable.</p>\n"
},
{
"answer_id": 9508230,
"author": "Mohammad Ahmed",
"author_id": 1098528,
"author_profile": "https://Stackoverflow.com/users/1098528",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>Clone()</code> method don't give reference to the target instance just give you a copy.\nthe <code>CopyTo()</code> method copies the elements into an existing instance.</p>\n\n<p>Both don't give the reference of the target instance and as many members says they give shallow copy (illusion copy) without reference this is the key.</p>\n"
},
{
"answer_id": 12141764,
"author": "João Angelo",
"author_id": 204699,
"author_profile": "https://Stackoverflow.com/users/204699",
"pm_score": 5,
"selected": false,
"text": "<p>As stated in many other answers both methods perform <a href=\"https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy\">shallow copies</a> of the array. However there are differences and recommendations that have not been addressed yet and that are highlighted in the following lists.</p>\n\n<p>Characteristics of <a href=\"http://msdn.microsoft.com/en-us/library/system.array.clone.aspx\" rel=\"noreferrer\"><code>System.Array.Clone</code></a>:</p>\n\n<ul>\n<li>Tests, using .NET 4.0, show that it <strong>is slower than <code>CopyTo</code></strong> probably because it uses <a href=\"http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx\" rel=\"noreferrer\"><code>Object.MemberwiseClone</code></a>;</li>\n<li><strong>Requires casting the result</strong> to the appropriate type;</li>\n<li>The resulting array has the same length as the source.</li>\n</ul>\n\n<p>Characteristics of <a href=\"http://msdn.microsoft.com/en-us/library/06x742cw.aspx\" rel=\"noreferrer\"><code>System.Array.CopyTo</code></a>:</p>\n\n<ul>\n<li><strong>Is faster than <code>Clone</code></strong> when copying to array of same type;</li>\n<li><strong>It calls into <a href=\"http://msdn.microsoft.com/en-us/library/system.array.constrainedcopy.aspx\" rel=\"noreferrer\"><code>Array.Copy</code></a> inheriting is capabilities</strong>, being the most useful ones:\n\n<ul>\n<li>Can box value type elements into reference type elements, for example, copying an <code>int[]</code> array into an <code>object[]</code>;</li>\n<li>Can unbox reference type elements into value type elements, for example, copying a <code>object[]</code> array of boxed <code>int</code> into an <code>int[]</code>;</li>\n<li>Can perform widening conversions on value types, for example, copying a <code>int[]</code> into a <code>long[]</code>.</li>\n<li>Can downcast elements, for example, copying a <code>Stream[]</code> array into a <code>MemoryStream[]</code> (if any element in source array is not convertible to <code>MemoryStream</code> an exception is thrown).</li>\n</ul></li>\n<li>Allows to copy the source to a target array that has a length greater than the source.</li>\n</ul>\n\n<p>Also note, these methods are made available to support <a href=\"http://msdn.microsoft.com/en-us/library/system.icloneable.aspx\" rel=\"noreferrer\"><code>ICloneable</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.icollection.aspx\" rel=\"noreferrer\"><code>ICollection</code></a>, so if you are dealing with variables of array types you should not use <code>Clone</code> or <code>CopyTo</code> and instead use <a href=\"http://msdn.microsoft.com/en-us/library/k4yx47a1.aspx\" rel=\"noreferrer\"><code>Array.Copy</code></a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.array.constrainedcopy.aspx\" rel=\"noreferrer\"><code>Array.ConstrainedCopy</code></a>. The constrained copy assures that if the copy operation cannot complete successful then the target array state is not corrupted. </p>\n"
},
{
"answer_id": 20470263,
"author": "inbaly",
"author_id": 2924987,
"author_profile": "https://Stackoverflow.com/users/2924987",
"pm_score": -1,
"selected": false,
"text": "<p>Please note: There is a difference between using String[] to StringBuilder[].</p>\n\n<p>In String - if you change the String, the other arrays we have copied (by CopyTo or Clone) that points to the same string will not change, but the original String array will point to a new String, however, if we use a StringBuilder in an array, the String pointer will not change, therefore, it will affect all the copies we have made for this array. For instance:</p>\n\n<pre><code>public void test()\n{\n StringBuilder[] sArrOr = new StringBuilder[1];\n sArrOr[0] = new StringBuilder();\n sArrOr[0].Append(\"hello\");\n StringBuilder[] sArrClone = (StringBuilder[])sArrOr.Clone();\n StringBuilder[] sArrCopyTo = new StringBuilder[1];\n sArrOr.CopyTo(sArrCopyTo,0);\n sArrOr[0].Append(\" world\");\n\n Console.WriteLine(sArrOr[0] + \" \" + sArrClone[0] + \" \" + sArrCopyTo[0]);\n //Outputs: hello world hello world hello world\n\n //Same result in int[] as using String[]\n int[] iArrOr = new int[2];\n iArrOr[0] = 0;\n iArrOr[1] = 1;\n int[] iArrCopyTo = new int[2];\n iArrOr.CopyTo(iArrCopyTo,0);\n int[] iArrClone = (int[])iArrOr.Clone();\n iArrOr[0]++;\n Console.WriteLine(iArrOr[0] + \" \" + iArrClone[0] + \" \" + iArrCopyTo[0]);\n // Output: 1 0 0\n}\n</code></pre>\n"
},
{
"answer_id": 43382728,
"author": "Nikhil Redij",
"author_id": 7802556,
"author_profile": "https://Stackoverflow.com/users/7802556",
"pm_score": 0,
"selected": false,
"text": "<p>Both are shallow copies. <strong>CopyTo method is not a deep copy.</strong>\nCheck the following code :</p>\n\n<pre><code>public class TestClass1\n{\n public string a = \"test1\";\n}\n\npublic static void ArrayCopyClone()\n{\n TestClass1 tc1 = new TestClass1();\n TestClass1 tc2 = new TestClass1();\n\n TestClass1[] arrtest1 = { tc1, tc2 };\n TestClass1[] arrtest2 = new TestClass1[arrtest1.Length];\n TestClass1[] arrtest3 = new TestClass1[arrtest1.Length];\n\n arrtest1.CopyTo(arrtest2, 0);\n arrtest3 = arrtest1.Clone() as TestClass1[];\n\n Console.WriteLine(arrtest1[0].a);\n Console.WriteLine(arrtest2[0].a);\n Console.WriteLine(arrtest3[0].a);\n\n arrtest1[0].a = \"new\";\n\n Console.WriteLine(arrtest1[0].a);\n Console.WriteLine(arrtest2[0].a);\n Console.WriteLine(arrtest3[0].a);\n}\n\n/* Output is \ntest1\ntest1\ntest1\nnew\nnew\nnew */\n</code></pre>\n"
},
{
"answer_id": 57072754,
"author": "Aikansh Mann",
"author_id": 6578251,
"author_profile": "https://Stackoverflow.com/users/6578251",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Array.Clone</strong> doesn't require a target/destination array to be available when calling the function, whereas <strong>Array.CopyTo</strong> requires a destination array and an index.</p>\n"
},
{
"answer_id": 63319470,
"author": "Umasankar Siva",
"author_id": 14072525,
"author_profile": "https://Stackoverflow.com/users/14072525",
"pm_score": 1,
"selected": false,
"text": "<p><code>Array.Clone()</code> would perform technically deep copy, when pass the array of <code>int</code> or string to a method as a reference.</p>\n<p>For example</p>\n<pre><code>int[] numbers = new int[] { -11, 12, -42, 0, 1, 90, 68, 6, -9 }; \n\nSortByAscending(numbers); // Sort the array in ascending order by clone the numbers array to local new array.\nSortByDescending(numbers); // Same as Ascending order Clone\n</code></pre>\n<p>Even if the methods sort the array of numbers but it wont affect the actual reference passed to the sorting methods.i.e the number array will be in same unsorted initial format in line no 1.</p>\n<p><strong>Note:</strong> The Clone should be done in the sorting methods.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
] |
What’s the difference between the `System.Array.CopyTo()` and `System.Array.Clone()`?
|
The **[Clone()](http://msdn.microsoft.com/en-us/library/system.array.clone.aspx)** method returns a new array (a shallow copy) object containing all the elements in the original array. The **[CopyTo()](http://msdn.microsoft.com/en-us/library/system.array.copyto.aspx)** method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.
So the difference are :
```
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.
```
Edit:
Remove the wrong example.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.