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
|
---|---|---|---|---|---|---|
229,765 |
<p>In cleaning up <a href="https://stackoverflow.com/questions/229447/how-to-create-a-two-sided-unique-index-on-two-fields#229521">this answer</a> I learnt a bit about <code>TRIGGER</code>s and stored procedures in MySQL, but was stunned that, while <code>BEFORE INSERT</code> and <code>BEFORE UPDATE</code> triggers could modify data, they seemingly couldn't cause the insert/update to fail (ie. validation). In this particular case I was able to get this to work by manipulating the data in such a way as to cause a primary key duplicate, which in this particular case made sense, but doesn't necessarily make sense in a general sense.</p>
<p>Is this sort of functionality possible in MySQL? In any other RDBMS (my experience is limited to MySQL sadly)? Perhaps a <code>THROW EXCEPTION</code> style syntax?</p>
|
[
{
"answer_id": 229802,
"author": "Esteban Brenes",
"author_id": 14177,
"author_profile": "https://Stackoverflow.com/users/14177",
"pm_score": 5,
"selected": true,
"text": "<p>From this <a href=\"https://web.archive.org/web/20180330233216/http://www.brokenbuild.com/blog/2006/08/15/mysql-triggers-how-do-you-abort-an-insert-update-or-delete-with-a-trigger/\" rel=\"nofollow noreferrer\">blog post</a></p>\n\n<blockquote>\n <p>MySQL Triggers: How do you abort an INSERT, UPDATE or DELETE with a\n trigger? On EfNet’s #mysql someone\n asked:</p>\n \n <p><em>How do I make a trigger abort the operation if my business rule fails?</em></p>\n \n <p>In MySQL 5.0 and 5.1 you need to\n resort to some trickery to make a\n trigger fail and deliver a meaningful\n error message. The MySQL Stored\n Procedure FAQ says this about error\n handling:</p>\n \n <p><em>SP 11. Do SPs have a “raise” statement to “raise application errors”? Sorry, not at present. The SQL standard SIGNAL and RESIGNAL statements are on the TODO.</em></p>\n \n <p>Perhaps MySQL 5.2 will include SIGNAL\n statement which will make this hack\n stolen straight from MySQL Stored\n Procedure Programming obsolete. What\n is the hack? You’re going to force\n MySQL to attempt to use a column that\n does not exist. Ugly? Yes. Does it\n work? Sure.</p>\n\n<pre><code>CREATE TRIGGER mytabletriggerexample\nBEFORE INSERT\nFOR EACH ROW BEGIN\nIF(NEW.important_value) < (fancy * dancy * calculation) THEN\n DECLARE dummy INT;\n\n SELECT Your meaningful error message goes here INTO dummy \n FROM mytable\n WHERE mytable.id=new.id\nEND IF; END;\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 229821,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 1,
"selected": false,
"text": "<p>This will abort your INSERT by raising an exception (from <a href=\"http://www.experts-exchange.com/Database/MySQL/Q_23788965.html\" rel=\"nofollow noreferrer\">http://www.experts-exchange.com/Database/MySQL/Q_23788965.html</a>)</p>\n\n<pre><code>DROP PROCEDURE IF EXISTS `MyRaiseError`$$\n\nCREATE PROCEDURE `MyRaiseError`(msg VARCHAR(62))\nBEGIN\nDECLARE Tmsg VARCHAR(80);\nSET Tmsg = msg;\nIF (CHAR_LENGTH(TRIM(Tmsg)) = 0 OR Tmsg IS NULL) THEN\nSET Tmsg = 'ERROR GENERADO';\nEND IF;\nSET Tmsg = CONCAT('@@MyError', Tmsg, '@@MyError');\nSET @MyError = CONCAT('INSERT INTO', Tmsg);\nPREPARE stmt FROM @MyError;\nEXECUTE stmt;\nDEALLOCATE PREPARE stmt;\nEND$$\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>call MyRaiseError('Here error message!');\n</code></pre>\n"
},
{
"answer_id": 229828,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": -1,
"selected": false,
"text": "<p>in MS SQL you could make it work using proper syntax:</p>\n\n<pre><code>IF UPDATE(column_name)\nBEGIN\n RAISEERROR\n ROLLBACK TRAN\n RETURN\nEND\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc164047.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc164047.aspx</a></p>\n"
},
{
"answer_id": 2694100,
"author": "PCPGMR",
"author_id": 323650,
"author_profile": "https://Stackoverflow.com/users/323650",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the way I did it. Note the <code>SET NEW='some error';</code>. MySQL will tell you \"Variable 'new' can't be set to the value of 'Error: Cannot delete this item. There are records in the sales table with this item.'\" </p>\n\n<p>You can trap this in your code and then show the resulting error :)</p>\n\n<pre><code>DELIMITER $$\nDROP TRIGGER IF EXISTS before_tblinventoryexceptionreasons_delete $$\nCREATE TRIGGER before_tblinventoryexceptionreasons_delete\nBEFORE DELETE ON tblinventoryexceptionreasons\nFOR EACH ROW BEGIN\n IF (SELECT COUNT(*) FROM tblinventoryexceptions WHERE tblinventoryexceptions.idtblinventoryexceptionreasons = old.idtblinventoryexceptionreasons) > 0\n THEN\n SET NEW='Error: Cannot delete this item. There are records in the inventory exception reasons table with this item.';\n END IF;\nEND$$\nDELIMITER ;\n\nDELIMITER $$\nDROP TRIGGER IF EXISTS before_storesalesconfig_delete $$\nCREATE TRIGGER before_storesalesconfig_delete\nBEFORE DELETE ON tblstoresalesconfig\nFOR EACH ROW BEGIN\n IF (SELECT COUNT(*) FROM tblstoresales WHERE tblstoresales.idtblstoresalesconfig=old.idtblstoresalesconfig) > 0\n THEN\n SET NEW='Error: Cannot delete this item. There are records in the sales table with this item.';\n END IF;\n IF (SELECT COUNT(*) FROM tblinventory WHERE tblinventory.idtblstoresalesconfig=old.idtblstoresalesconfig) > 0\n THEN\n SET NEW='Error: Cannot delete this item. There are records in the inventory table with this item.';\n END IF;\n IF (SELECT COUNT(*) FROM tblinventoryexceptions WHERE tblinventoryexceptions.idtblstoresalesconfig=old.idtblstoresalesconfig) > 0\n THEN\n SET NEW='Error: Cannot delete this item. There are records in the inventory exceptions table with this item.';\n END IF;\n IF (SELECT COUNT(*) FROM tblinvoicedetails WHERE tblinvoicedetails.idtblstoresalesconfig=old.idtblstoresalesconfig) > 0\n THEN\n SET NEW='Error: Cannot delete this item. There are records in the inventory details table with this item.';\n END IF;\nEND$$\nDELIMITER ;\n\nDELIMITER $$\nDROP TRIGGER IF EXISTS before_tblinvoice_delete $$\nCREATE TRIGGER before_tblinvoice_delete\nBEFORE DELETE ON tblinvoice\nFOR EACH ROW BEGIN\n IF (SELECT COUNT(*) FROM tblinvoicedetails WHERE tblinvoicedetails.idtblinvoice = old.idtblinvoice) > 0\n THEN\n SET NEW='Error: Cannot delete this item. There are records in the inventory details table with this item.';\n END IF;\nEND$$\nDELIMITER ;\n</code></pre>\n"
},
{
"answer_id": 11318648,
"author": "Karel Ruland",
"author_id": 1499915,
"author_profile": "https://Stackoverflow.com/users/1499915",
"pm_score": 1,
"selected": false,
"text": "<p>Doen't work in triggers\n(Dynamic SQL is not allowed in stored function or trigger)</p>\n\n<p>I use a very dirty solution:</p>\n\n<p><code>If NEW.test=1 then\n CALL TEST_CANNOT_BE_SET_TO_1;\nend if;\n</code></p>\n\n<p>When test=1 Mysql throws the following exception: </p>\n\n<p>PROCEDURE administratie.TEST_CANNOT_BE_SET_TO_1 does not exist</p>\n\n<p>Not sophisticated but fast and usefull.</p>\n"
},
{
"answer_id": 26115231,
"author": "Kyle Johnson",
"author_id": 1733365,
"author_profile": "https://Stackoverflow.com/users/1733365",
"pm_score": 3,
"selected": false,
"text": "<p>Because this article comes up towards the top when I search for error handling in MySQL triggers, I thought I'd share some knowledge.</p>\n\n<p>If there is an error, you can force MySQL to use a <a href=\"http://dev.mysql.com/doc/refman/5.5/en/signal.html\" rel=\"noreferrer\" title=\"SIGNAL\">SIGNAL</a>, but if you don't specify it as a class as SQLEXCEPTION, then nothing will happen, as not all SQLSTATEs are considered bad, and even then you'd have to make sure to <a href=\"http://dev.mysql.com/doc/refman/5.5/en/resignal.html\" rel=\"noreferrer\" title=\"RESIGNAL\">RESIGNAL</a> if you have any nested BEGIN/END blocks.</p>\n\n<p>Alternatively, and probably simpler still, within your trigger, declare an exit handler and resignal the exception.</p>\n\n<pre><code>CREATE TRIGGER `my_table_AINS` AFTER INSERT ON `my_table` FOR EACH ROW\nBEGIN\n DECLARE EXIT HANDLER FOR SQLEXCEPTION\n RESIGNAL;\n DECLARE EXIT HANDLER FOR SQLWARNING\n RESIGNAL;\n DECLARE EXIT HANDLER FOR NOT FOUND\n RESIGNAL; \n -- Do the work of the trigger.\nEND\n</code></pre>\n\n<p>And if in your body there occurs an error, it will be thrown back up to the top and exit with an error. This can also be used in stored procedures and whatnot. </p>\n\n<p>This works with anything version 5.5+.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
In cleaning up [this answer](https://stackoverflow.com/questions/229447/how-to-create-a-two-sided-unique-index-on-two-fields#229521) I learnt a bit about `TRIGGER`s and stored procedures in MySQL, but was stunned that, while `BEFORE INSERT` and `BEFORE UPDATE` triggers could modify data, they seemingly couldn't cause the insert/update to fail (ie. validation). In this particular case I was able to get this to work by manipulating the data in such a way as to cause a primary key duplicate, which in this particular case made sense, but doesn't necessarily make sense in a general sense.
Is this sort of functionality possible in MySQL? In any other RDBMS (my experience is limited to MySQL sadly)? Perhaps a `THROW EXCEPTION` style syntax?
|
From this [blog post](https://web.archive.org/web/20180330233216/http://www.brokenbuild.com/blog/2006/08/15/mysql-triggers-how-do-you-abort-an-insert-update-or-delete-with-a-trigger/)
>
> MySQL Triggers: How do you abort an INSERT, UPDATE or DELETE with a
> trigger? On EfNet’s #mysql someone
> asked:
>
>
> *How do I make a trigger abort the operation if my business rule fails?*
>
>
> In MySQL 5.0 and 5.1 you need to
> resort to some trickery to make a
> trigger fail and deliver a meaningful
> error message. The MySQL Stored
> Procedure FAQ says this about error
> handling:
>
>
> *SP 11. Do SPs have a “raise” statement to “raise application errors”? Sorry, not at present. The SQL standard SIGNAL and RESIGNAL statements are on the TODO.*
>
>
> Perhaps MySQL 5.2 will include SIGNAL
> statement which will make this hack
> stolen straight from MySQL Stored
> Procedure Programming obsolete. What
> is the hack? You’re going to force
> MySQL to attempt to use a column that
> does not exist. Ugly? Yes. Does it
> work? Sure.
>
>
>
> ```
> CREATE TRIGGER mytabletriggerexample
> BEFORE INSERT
> FOR EACH ROW BEGIN
> IF(NEW.important_value) < (fancy * dancy * calculation) THEN
> DECLARE dummy INT;
>
> SELECT Your meaningful error message goes here INTO dummy
> FROM mytable
> WHERE mytable.id=new.id
> END IF; END;
>
> ```
>
>
|
229,824 |
<p>Ok, there are a million regexes out there for validating an email address, but how about some basic email validation that can be integrated into a TSQL query for Sql Server 2005?</p>
<p>I don't want to use a CLR procedure or function. Just straight TSQL.</p>
<p>Has anybody tackled this already?</p>
|
[
{
"answer_id": 229955,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 7,
"selected": true,
"text": "<p><em>Very</em> basic would be:</p>\n\n<pre><code>SELECT\n EmailAddress, \n CASE WHEN EmailAddress LIKE '%_@_%_.__%' \n AND EmailAddress NOT LIKE '%[any obviously invalid characters]%' \n THEN 'Could be' \n ELSE 'Nope' \n END Validates\nFROM \n Table\n</code></pre>\n\n<p>This matches everything with an @ in the middle, preceded by at least one character, followed by at least two, a dot and at least two for the TLD.</p>\n\n<p>You can write more <code>LIKE</code> patterns that do more specific things, but you will never be able to match everything that could be an e-mail address while not letting slip through things that are not. Even with regular expressions you have a hard time doing it right. Additionally, even matching according to the very letters of the RFC matches address constructs that will not be accepted/used by most emailing systems.</p>\n\n<p>Doing this on the database level is maybe the wrong approach anyway, so a basic sanity check as indicated above may be the best you can get performance-wise, and doing it in an application will provide you with far greater flexibility.</p>\n"
},
{
"answer_id": 1345539,
"author": "cabgef",
"author_id": 99999,
"author_profile": "https://Stackoverflow.com/users/99999",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a sample function for this that's a little more detailed, I don't remember where I got this from (years ago), or if I modified it, otherwise I would include proper attribution:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnAppEmailCheck](@email VARCHAR(255)) \n--Returns true if the string is a valid email address. \nRETURNS bit \nas \nBEGIN \n DECLARE @valid bit \n IF @email IS NOT NULL \n SET @email = LOWER(@email) \n SET @valid = 0 \n IF @email like '[a-z,0-9,_,-]%@[a-z,0-9,_,-]%.[a-z][a-z]%' \n AND LEN(@email) = LEN(dbo.fnAppStripNonEmail(@email)) \n AND @email NOT like '%@%@%' \n AND CHARINDEX('.@',@email) = 0 \n AND CHARINDEX('..',@email) = 0 \n AND CHARINDEX(',',@email) = 0 \n AND RIGHT(@email,1) between 'a' AND 'z' \n SET @valid=1 \n RETURN @valid \nEND \n</code></pre>\n"
},
{
"answer_id": 2809784,
"author": "payonk",
"author_id": 338141,
"author_profile": "https://Stackoverflow.com/users/338141",
"pm_score": -1,
"selected": false,
"text": "<p>From Tomalak's slelect</p>\n\n<pre><code>select 1\nwhere @email not like '%[^a-z,0-9,@,.]%'\nand @email like '%_@_%_.__%'\n</code></pre>\n"
},
{
"answer_id": 25978991,
"author": "Mike Wallace",
"author_id": 4067421,
"author_profile": "https://Stackoverflow.com/users/4067421",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Create Function [dbo].[fnAppStripNonEmail](@Temp VarChar(1000))\nReturns VarChar(1000)\nAS\nBegin\n\n Declare @KeepValues as varchar(50)\n Set @KeepValues = '%[^a-z,0-9,@,.,-]%'\n While PatIndex(@KeepValues, @Temp) > 0\n Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')\n\n Return @Temp\nEnd\n</code></pre>\n"
},
{
"answer_id": 28962448,
"author": "HamzeLue",
"author_id": 3104189,
"author_profile": "https://Stackoverflow.com/users/3104189",
"pm_score": 0,
"selected": false,
"text": "<p>This is the easiest way to select them.</p>\n\n<p>Use this query</p>\n\n<pre><code>SELECT * FROM <TableName> WHERE [EMail] NOT LIKE '%_@__%.__%'\n</code></pre>\n"
},
{
"answer_id": 35160236,
"author": "Tony Dong",
"author_id": 760139,
"author_profile": "https://Stackoverflow.com/users/760139",
"pm_score": 1,
"selected": false,
"text": "<p>FnAppStripNonEmail missing under score, need add it to the keep values</p>\n\n<pre><code>Create Function [dbo].[fnAppStripNonEmail](@Temp VarChar(1000))\nReturns VarChar(1000)\nAS\nBegin\n\n Declare @KeepValues as varchar(50)\n Set @KeepValues = '%[^a-z,0-9,_,@,.,-]%'\n While PatIndex(@KeepValues, @Temp) > 0\n Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')\n\n Return @Temp\nEnd\n</code></pre>\n"
},
{
"answer_id": 37491215,
"author": "James",
"author_id": 1887946,
"author_profile": "https://Stackoverflow.com/users/1887946",
"pm_score": 2,
"selected": false,
"text": "<p>Great answers! Based these recommendations I came up with a simplified function that combines the best 2 answers.</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnIsValidEmail]\n(\n @email varchar(255)\n) \n--Returns true if the string is a valid email address. \nRETURNS bit \nAs \nBEGIN\n RETURN CASE WHEN ISNULL(@email, '') <> '' AND @email LIKE '%_@%_.__%' THEN 1 ELSE 0 END\nEND\n</code></pre>\n"
},
{
"answer_id": 43589857,
"author": "Roy Gelerman",
"author_id": 7914057,
"author_profile": "https://Stackoverflow.com/users/7914057",
"pm_score": 1,
"selected": false,
"text": "<pre><code>CREATE FUNCTION fnIsValidEmail\n(\n @email varchar(255)\n)\nRETURNS bit\nAS\nBEGIN\n\n DECLARE @IsValidEmail bit = 0\n\n IF (@email not like '%[^a-z,0-9,@,.,!,#,$,%%,&,'',*,+,--,/,=,?,^,_,`,{,|,},~]%' --First Carat ^ means Not these characters in the LIKE clause. The list is the valid email characters.\n AND @email like '%_@_%_.[a-z,0-9][a-z]%'\n AND @email NOT like '%@%@%' \n AND @email NOT like '%..%'\n AND @email NOT like '.%'\n AND @email NOT like '%.'\n AND CHARINDEX('@', @email) <= 65\n )\n BEGIN\n SET @IsValidEmail = 1\n END\n\n RETURN @IsValidEmail\n\nEND\n</code></pre>\n"
},
{
"answer_id": 47350807,
"author": "Esperento57",
"author_id": 3735690,
"author_profile": "https://Stackoverflow.com/users/3735690",
"pm_score": 2,
"selected": false,
"text": "<p>On SQL 2016 or +</p>\n\n<pre><code>CREATE FUNCTION [DBO].[F_IsEmail] (\n @EmailAddr varchar(360) -- Email address to check\n) RETURNS BIT -- 1 if @EmailAddr is a valid email address\n\nAS BEGIN\nDECLARE @AlphabetPlus VARCHAR(255)\n , @Max INT -- Length of the address\n , @Pos INT -- Position in @EmailAddr\n , @OK BIT -- Is @EmailAddr OK\n-- Check basic conditions\nIF @EmailAddr IS NULL \n OR @EmailAddr NOT LIKE '[0-9a-zA-Z]%@__%.__%' \n OR @EmailAddr LIKE '%@%@%' \n OR @EmailAddr LIKE '%..%' \n OR @EmailAddr LIKE '%.@' \n OR @EmailAddr LIKE '%@.' \n OR @EmailAddr LIKE '%@%.-%' \n OR @EmailAddr LIKE '%@%-.%' \n OR @EmailAddr LIKE '%@-%' \n OR CHARINDEX(' ',LTRIM(RTRIM(@EmailAddr))) > 0\n RETURN(0)\n\n\n\ndeclare @AfterLastDot varchar(360);\ndeclare @AfterArobase varchar(360);\ndeclare @BeforeArobase varchar(360);\ndeclare @HasDomainTooLong bit=0;\n\n--Control des longueurs et autres incoherence\nset @AfterLastDot=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('.',REVERSE(@EmailAddr))));\nif len(@AfterLastDot) not between 2 and 17\nRETURN(0);\n\nset @AfterArobase=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('@',REVERSE(@EmailAddr))));\nif len(@AfterArobase) not between 2 and 255\nRETURN(0);\n\nselect top 1 @BeforeArobase=value from string_split(@EmailAddr, '@');\nif len(@AfterArobase) not between 2 and 255\nRETURN(0);\n\n--Controle sous-domain pas plus grand que 63\nselect top 1 @HasDomainTooLong=1 from string_split(@AfterArobase, '.') where LEN(value)>63\nif @HasDomainTooLong=1\nreturn(0);\n\n--Control de la partie locale en detail\nSELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890!#$%&‘*+-/=?^_`.{|}~'\n , @Max = LEN(@BeforeArobase)\n , @Pos = 0\n , @OK = 1\n\n\nWHILE @Pos < @Max AND @OK = 1 BEGIN\n SET @Pos = @Pos + 1\n IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@BeforeArobase, @Pos, 1) + '%' \n SET @OK = 0\nEND\n\nif @OK=0\nRETURN(0);\n\n--Control de la partie domaine en detail\nSELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890-.'\n , @Max = LEN(@AfterArobase)\n , @Pos = 0\n , @OK = 1\n\nWHILE @Pos < @Max AND @OK = 1 BEGIN\n SET @Pos = @Pos + 1\n IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@AfterArobase, @Pos, 1) + '%' \n SET @OK = 0\nEND\n\nif @OK=0\nRETURN(0);\n\n\n\n\n\n\n\nreturn(1);\n\n\n\nEND\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] |
Ok, there are a million regexes out there for validating an email address, but how about some basic email validation that can be integrated into a TSQL query for Sql Server 2005?
I don't want to use a CLR procedure or function. Just straight TSQL.
Has anybody tackled this already?
|
*Very* basic would be:
```
SELECT
EmailAddress,
CASE WHEN EmailAddress LIKE '%_@_%_.__%'
AND EmailAddress NOT LIKE '%[any obviously invalid characters]%'
THEN 'Could be'
ELSE 'Nope'
END Validates
FROM
Table
```
This matches everything with an @ in the middle, preceded by at least one character, followed by at least two, a dot and at least two for the TLD.
You can write more `LIKE` patterns that do more specific things, but you will never be able to match everything that could be an e-mail address while not letting slip through things that are not. Even with regular expressions you have a hard time doing it right. Additionally, even matching according to the very letters of the RFC matches address constructs that will not be accepted/used by most emailing systems.
Doing this on the database level is maybe the wrong approach anyway, so a basic sanity check as indicated above may be the best you can get performance-wise, and doing it in an application will provide you with far greater flexibility.
|
229,851 |
<p>Is there a way to unlock Windows files without downloading a utility?</p>
<p>I have a few files on my Windows XP C: drive that are very old and very useless. When I try to delete these files I get the following message:</p>
<pre>
Cannot delete FILENAME.zip: It is being used by another person or program
Close any programs that might be using the file and try again.
</pre>
<p>No one is accessing this file. No program is using it currently. Windows has screwed up the file locking mechanism. </p>
<p>Is there a way to delete this file without downloading someone's unlocking utility? I find the sites offering these programs to be a tad sketchy.</p>
<p>How could you force the file to unlock from within a program? I'm competent in Java, Perl, and Ruby, but I haven't seen anything among their libraries that would aid me here.</p>
|
[
{
"answer_id": 229859,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "<p>If you reboot and the files are still locked, then there is some process on your machine that <strong>is</strong> still using them. First you should figure out what that process is and determine if the files really aren't used any more or not.</p>\n"
},
{
"answer_id": 229878,
"author": "branchgabriel",
"author_id": 30807,
"author_profile": "https://Stackoverflow.com/users/30807",
"pm_score": 2,
"selected": false,
"text": "<p>Use msconfig and start up with everything turned off.</p>\n\n<p>Then try to move / delete the file.</p>\n\n<p>Or you can always boot up in safe mode and delete it.</p>\n\n<p>You do that by hitting f8 when the machine boots up.</p>\n"
},
{
"answer_id": 229879,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 3,
"selected": false,
"text": "<p>Did you try the commandline command <a href=\"http://technet.microsoft.com/en-us/library/cc732490.aspx\" rel=\"noreferrer\">OpenFiles</a></p>\n\n<p>It is built in (XP and above I believe) and has several arguments that can be passed in.</p>\n"
},
{
"answer_id": 229894,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 6,
"selected": true,
"text": "<p>I've successfully used Process Explorer to find out which process has the file open. It saves a reboot that may not fix the problem anyway.</p>\n<p>In process explorer: Find > Handle or DLL... then search for the name of the folder/file, then double click one of the search results. It'll select a handle in the main window, which you can right click and close.</p>\n"
},
{
"answer_id": 229984,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 1,
"selected": false,
"text": "<p>Rebooting to Safe Mode is often a very easy way to do it. When you boot in safe mode, it won't load all the stuff set to run on startup. Press F8 while it's booting to access the boot menu, and choose \"safe mode\".</p>\n"
},
{
"answer_id": 230965,
"author": "Pradeep",
"author_id": 29693,
"author_profile": "https://Stackoverflow.com/users/29693",
"pm_score": 3,
"selected": false,
"text": "<p>Try downloading \"Unlocker\". Google it and take my words that it doesn't have any worm/spyware/virus. It is pretty cool utility and works great. Give it a try.</p>\n"
},
{
"answer_id": 234038,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need any utility.\nJust use Win32 api to unlock them (simply close the handle)</p>\n"
},
{
"answer_id": 12147315,
"author": "Steve",
"author_id": 1628408,
"author_profile": "https://Stackoverflow.com/users/1628408",
"pm_score": 1,
"selected": false,
"text": "<p>I had a .jpg pfile that hasd that issue and I couldn't delete. That brought me to this thread. When nothing else worked I renamed the file and left off the .jpg. THEN I could delete it easily. Not sure why, but worked for me</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8344/"
] |
Is there a way to unlock Windows files without downloading a utility?
I have a few files on my Windows XP C: drive that are very old and very useless. When I try to delete these files I get the following message:
```
Cannot delete FILENAME.zip: It is being used by another person or program
Close any programs that might be using the file and try again.
```
No one is accessing this file. No program is using it currently. Windows has screwed up the file locking mechanism.
Is there a way to delete this file without downloading someone's unlocking utility? I find the sites offering these programs to be a tad sketchy.
How could you force the file to unlock from within a program? I'm competent in Java, Perl, and Ruby, but I haven't seen anything among their libraries that would aid me here.
|
I've successfully used Process Explorer to find out which process has the file open. It saves a reboot that may not fix the problem anyway.
In process explorer: Find > Handle or DLL... then search for the name of the folder/file, then double click one of the search results. It'll select a handle in the main window, which you can right click and close.
|
229,856 |
<p>What is the best way to save enums into a database?</p>
<p>I know Java provides <code>name()</code> and <code>valueOf()</code> methods to convert enum values into a String and back. But are there any other (flexible) options to store these values?</p>
<p>Is there a smart way to make enums into unique numbers (<code>ordinal()</code> is not safe to use)?</p>
<h4>Update</h4>
<p>Thanks for all awesome and fast answers! It was as I suspected.</p>
<p>However, a note to <a href="https://stackoverflow.com/users/3295">toolkit</a>: That is one way. The problem is that I would have to add the same methods to each enum type that I create. That's a lot of duplicated code and, at the moment, Java does not support any solutions for this (a Java enum cannot extend other classes).</p>
|
[
{
"answer_id": 229902,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 3,
"selected": false,
"text": "<p>I would argue that the only safe mechanism here is to use the String <code>name()</code> value. When writing to the DB, you <em>could</em> use a sproc to insert the value and when reading, use a View. In this manner, if the enums change, there is a level of indirection in the sproc/view to be able to present the data as the enum value without \"imposing\" this on the DB.</p>\n"
},
{
"answer_id": 229919,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 9,
"selected": true,
"text": "<p>We <em>never</em> store enumerations as numerical ordinal values anymore; it makes debugging and support way too difficult. We store the actual enumeration value converted to string:</p>\n<pre><code>public enum Suit { Spade, Heart, Diamond, Club }\n\nSuit theSuit = Suit.Heart;\n\nszQuery = "INSERT INTO Customers (Name, Suit) " +\n "VALUES ('Ian Boyd', %s)".format(theSuit.name());\n</code></pre>\n<p>and then read back with:</p>\n<pre><code>Suit theSuit = Suit.valueOf(reader["Suit"]);\n</code></pre>\n<p>The problem was in the past staring at Enterprise Manager and trying to decipher:</p>\n<pre><code>Name Suit\n------------ ----\nKylie Guénin 2\nIan Boyd 1\n</code></pre>\n<p>verses</p>\n<pre><code>Name Suit\n------------ -------\nKylie Guénin Diamond\nIan Boyd Heart\n</code></pre>\n<p>the latter is much easier. The former required getting at the source code and finding the numerical values that were assigned to the enumeration members.</p>\n<p>Yes it takes more space, but the enumeration member names are short, and hard drives are cheap, and it is much more worth it to help when you're having a problem.</p>\n<p>Additionally, if you use numerical values, you are tied to them. You cannot nicely insert or rearrange the members without having to force the old numerical values. For example, changing the Suit enumeration to:</p>\n<pre><code>public enum Suit { Unknown, Heart, Club, Diamond, Spade }\n</code></pre>\n<p>would have to become :</p>\n<pre><code>public enum Suit { \n Unknown = 4,\n Heart = 1,\n Club = 3,\n Diamond = 2,\n Spade = 0 }\n</code></pre>\n<p>in order to maintain the legacy numerical values stored in the database.</p>\n<h2>How to sort them in the database</h2>\n<p>The question comes up: lets say i wanted to order the values. Some people may want to sort them by the <code>enum</code>'s ordinal value. Of course, ordering the cards by the numerical value of the enumeration is meaningless:</p>\n<pre><code>SELECT Suit FROM Cards\nORDER BY SuitID; --where SuitID is integer value(4,1,3,2,0)\n\nSuit\n------\nSpade\nHeart\nDiamond\nClub\nUnknown\n</code></pre>\n<p>That's not the order we want - we want them in enumeration order:</p>\n<pre><code>SELECT Suit FROM Cards\nORDER BY CASE SuitID OF\n WHEN 4 THEN 0 --Unknown first\n WHEN 1 THEN 1 --Heart\n WHEN 3 THEN 2 --Club\n WHEN 2 THEN 3 --Diamond\n WHEN 0 THEN 4 --Spade\n ELSE 999 END\n</code></pre>\n<p>The same work that is required if you save integer values is required if you save strings:</p>\n<pre><code>SELECT Suit FROM Cards\nORDER BY Suit; --where Suit is an enum name\n\nSuit\n-------\nClub\nDiamond\nHeart\nSpade\nUnknown\n</code></pre>\n<p>But that's not the order we want - we want them in enumeration order:</p>\n<pre><code>SELECT Suit FROM Cards\nORDER BY CASE Suit OF\n WHEN 'Unknown' THEN 0\n WHEN 'Heart' THEN 1\n WHEN 'Club' THEN 2\n WHEN 'Diamond' THEN 3\n WHEN 'Space' THEN 4\n ELSE 999 END\n</code></pre>\n<p>My opinion is that this kind of ranking belongs in the user interface. If you are sorting items based on their enumeration value: you're doing something wrong.</p>\n<p>But if you wanted to really do that, i would create a <code>Suits</code> <a href=\"https://en.wikipedia.org/wiki/Dimension_(data_warehouse)\" rel=\"noreferrer\">dimension table</a>:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Suit</th>\n<th>SuitID</th>\n<th>Rank</th>\n<th>Color</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Unknown</td>\n<td>4</td>\n<td>0</td>\n<td>NULL</td>\n</tr>\n<tr>\n<td>Heart</td>\n<td>1</td>\n<td>1</td>\n<td>Red</td>\n</tr>\n<tr>\n<td>Club</td>\n<td>3</td>\n<td>2</td>\n<td>Black</td>\n</tr>\n<tr>\n<td>Diamond</td>\n<td>2</td>\n<td>3</td>\n<td>Red</td>\n</tr>\n<tr>\n<td>Spade</td>\n<td>0</td>\n<td>4</td>\n<td>Black</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>This way, when you want to change your cards to use <a href=\"https://www.quora.com/When-you-buy-a-deck-of-cards-does-it-come-mixed-or-in-order\" rel=\"noreferrer\"><strong><em>Kissing Kings</em> New Deck Order</strong></a> you can change it for display purposes without throwing away all your data:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Suit</th>\n<th>SuitID</th>\n<th>Rank</th>\n<th>Color</th>\n<th>CardOrder</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Unknown</td>\n<td>4</td>\n<td>0</td>\n<td>NULL</td>\n<td>NULL</td>\n</tr>\n<tr>\n<td>Spade</td>\n<td>0</td>\n<td>1</td>\n<td>Black</td>\n<td>1</td>\n</tr>\n<tr>\n<td>Diamond</td>\n<td>2</td>\n<td>2</td>\n<td>Red</td>\n<td>1</td>\n</tr>\n<tr>\n<td>Club</td>\n<td>3</td>\n<td>3</td>\n<td>Black</td>\n<td>-1</td>\n</tr>\n<tr>\n<td>Heart</td>\n<td>1</td>\n<td>4</td>\n<td>Red</td>\n<td>-1</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Now we are separating an internal programming detail (enumeration name, enumeration value) with a display setting meant for users:</p>\n<pre><code>SELECT Cards.Suit \nFROM Cards\n INNER JOIN Suits ON Cards.Suit = Suits.Suit\nORDER BY Suits.Rank, \n Card.Rank*Suits.CardOrder\n \n</code></pre>\n"
},
{
"answer_id": 229936,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": false,
"text": "<p>As you say, ordinal is a bit risky. Consider for example:</p>\n\n<pre><code>public enum Boolean {\n TRUE, FALSE\n}\n\npublic class BooleanTest {\n @Test\n public void testEnum() {\n assertEquals(0, Boolean.TRUE.ordinal());\n assertEquals(1, Boolean.FALSE.ordinal());\n }\n}\n</code></pre>\n\n<p>If you stored this as ordinals, you might have rows like:</p>\n\n<pre><code>> SELECT STATEMENT, TRUTH FROM CALL_MY_BLUFF\n\n\"Alice is a boy\" 1\n\"Graham is a boy\" 0\n</code></pre>\n\n<p>But what happens if you updated Boolean?</p>\n\n<pre><code>public enum Boolean {\n TRUE, FILE_NOT_FOUND, FALSE\n}\n</code></pre>\n\n<p>This means all your lies will become misinterpreted as 'file-not-found'</p>\n\n<p>Better to just use a string representation</p>\n"
},
{
"answer_id": 230000,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 3,
"selected": false,
"text": "<p>We just store the enum name itself. It's more readable.</p>\n<p>We did mess around with adding an additional property to the enum where the enum has a limited set of values. For example, in the following enum, we use a <code>char</code> property to represent the enum value in the database (a <code>char</code> is more meaningful than a numeric value):</p>\n<pre><code>public enum EmailStatus {\n EMAIL_NEW('N'), EMAIL_SENT('S'), EMAIL_FAILED('F'), EMAIL_SKIPPED('K'), UNDEFINED('-');\n\n private char dbChar = '-';\n\n EmailStatus(char statusChar) {\n this.dbChar = statusChar;\n }\n\n public char statusChar() {\n return dbChar;\n }\n\n public static EmailStatus getFromStatusChar(char statusChar) {\n switch (statusChar) {\n case 'N':\n return EMAIL_NEW;\n case 'S':\n return EMAIL_SENT;\n case 'F':\n return EMAIL_FAILED;\n case 'K':\n return EMAIL_SKIPPED;\n default:\n return UNDEFINED;\n }\n }\n}\n</code></pre>\n<p>And when you have a lot of values, you can have a <code>Map</code> inside your enum to keep that <code>getFromXYZ</code> method small.</p>\n"
},
{
"answer_id": 230088,
"author": "Roger Durham",
"author_id": 29760,
"author_profile": "https://Stackoverflow.com/users/29760",
"pm_score": 2,
"selected": false,
"text": "<p>For a large database, I am reluctant to lose the size and speed advantages of the numeric representation. I often end up with a database table representing the Enum.</p>\n\n<p>You can enforce database consistency by declaring a foreign key -- although in some cases it might be better to not declare that as a foreign key constraint, which imposes a cost on every transaction. You can ensure consistency by periodically doing a check, at times of your choosing, with:</p>\n\n<pre><code>SELECT reftable.* FROM reftable\n LEFT JOIN enumtable ON reftable.enum_ref_id = enumtable.enum_id\nWHERE enumtable.enum_id IS NULL;\n</code></pre>\n\n<p>The other half of this solution is to write some test code that checks that the Java enum and the database enum table have the same contents. That's left as an exercise for the reader.</p>\n"
},
{
"answer_id": 230756,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 2,
"selected": false,
"text": "<p>If saving enums as strings in the database, you can create utility methods to (de)serialize any enum:</p>\n\n<pre><code> public static String getSerializedForm(Enum<?> enumVal) {\n String name = enumVal.name();\n // possibly quote value?\n return name;\n }\n\n public static <E extends Enum<E>> E deserialize(Class<E> enumType, String dbVal) {\n // possibly handle unknown values, below throws IllegalArgEx\n return Enum.valueOf(enumType, dbVal.trim());\n }\n\n // Sample use:\n String dbVal = getSerializedForm(Suit.SPADE);\n // save dbVal to db in larger insert/update ...\n Suit suit = deserialize(Suit.class, dbVal);\n</code></pre>\n"
},
{
"answer_id": 415595,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 6,
"selected": false,
"text": "<p>Unless you have specific performance reasons to avoid it, I would recommend using a separate table for the enumeration. Use foreign key integrity unless the extra lookup really kills you.</p>\n\n<h3>Suits table:</h3>\n\n<pre><code>suit_id suit_name\n1 Clubs\n2 Hearts\n3 Spades\n4 Diamonds\n</code></pre>\n\n<h3>Players table</h3>\n\n<pre><code>player_name suit_id\nIan Boyd 4\nShelby Lake 2\n</code></pre>\n\n<ol>\n<li>If you ever refactor your enumeration to be classes with behavior (such as priority), your database already models it correctly</li>\n<li>Your DBA is happy because your schema is normalized (storing a single integer per player, instead of an entire string, which may or may not have typos).</li>\n<li>Your database values (<code>suit_id</code>) are independent from your enumeration value, which helps you work on the data from other languages as well.</li>\n</ol>\n"
},
{
"answer_id": 9084379,
"author": "Kryszal",
"author_id": 869661,
"author_profile": "https://Stackoverflow.com/users/869661",
"pm_score": 1,
"selected": false,
"text": "<p>Multiple values with OR relation for one, enum field.\nThe concept for .NET with storing enum types in database like a byte or an int and using FlagsAttribute in your code.</p>\n\n<p><a href=\"http://blogs.msdn.com/b/efdesign/archive/2011/06/29/enumeration-support-in-entity-framework.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/efdesign/archive/2011/06/29/enumeration-support-in-entity-framework.aspx</a></p>\n"
},
{
"answer_id": 31329990,
"author": "Metaphore",
"author_id": 3802890,
"author_profile": "https://Stackoverflow.com/users/3802890",
"pm_score": 2,
"selected": false,
"text": "<p>All my experience tells me that safest way of persisting enums anywhere is to use an additional code value or id (some kind of evolution of <a href=\"https://stackoverflow.com/a/230000/1071320\">JeeBee's answer</a>). This could be a nice example of an idea:</p>\n<pre><code>enum Race {\n HUMAN ("human"),\n ELF ("elf"),\n DWARF ("dwarf");\n\n private final String code;\n\n private Race(String code) {\n this.code = code;\n }\n\n public String getCode() {\n return code;\n }\n}\n</code></pre>\n<p>Now you can go with any persistence referencing your enum constants by its code. Even if you decide to change some of the constant names, you always can save the code value (e.g. <code>DWARF("dwarf")</code> to <code>GNOME("dwarf")</code>).</p>\n<p>Ok, dive some more deeper with this conception. Here is some utility method, that helps you find any enum value, but first lets extend our approach.</p>\n<pre><code>interface CodeValue {\n String getCode();\n}\n</code></pre>\n<p>And let our enum implement it:</p>\n<pre><code>enum Race implement CodeValue {...}\n</code></pre>\n<p>This is the time for magic search method:</p>\n<pre><code>static <T extends Enum & CodeValue> T resolveByCode(Class<T> enumClass, String code) {\n T[] enumConstants = enumClass.getEnumConstants();\n for (T entry : enumConstants) {\n if (entry.getCode().equals(code)) return entry;\n }\n // In case we failed to find it, return null.\n // I'd recommend you make some log record here to get notified about wrong logic, perhaps.\n return null;\n}\n</code></pre>\n<p>And use it like a charm: <code>Race race = resolveByCode(Race.class, "elf")</code></p>\n"
},
{
"answer_id": 37473149,
"author": "SaravanaC",
"author_id": 6328496,
"author_profile": "https://Stackoverflow.com/users/6328496",
"pm_score": 3,
"selected": false,
"text": "<p>I have faced the same issue where my objective is to persist Enum String value into database instead of Ordinal value. </p>\n\n<p>To over come this issue, I have used <code>@Enumerated(EnumType.STRING)</code> and my objective got resolved.</p>\n\n<p>For Example, you have an <code>Enum</code> Class:</p>\n\n<pre><code>public enum FurthitMethod {\n\n Apple,\n Orange,\n Lemon\n}\n</code></pre>\n\n<p>In the entity class, define <code>@Enumerated(EnumType.STRING)</code>:</p>\n\n<pre><code>@Enumerated(EnumType.STRING)\n@Column(name = \"Fruits\")\npublic FurthitMethod getFuritMethod() {\n return fruitMethod;\n}\n\npublic void setFruitMethod(FurthitMethod authenticationMethod) {\n this.fruitMethod= fruitMethod;\n}\n</code></pre>\n\n<p>While you try to set your value to Database, String value will be persisted into Database as \"<code>APPLE</code>\", \"<code>ORANGE</code>\" or \"<code>LEMON</code>\".</p>\n"
},
{
"answer_id": 59575547,
"author": "Erk",
"author_id": 386587,
"author_profile": "https://Stackoverflow.com/users/386587",
"pm_score": 0,
"selected": false,
"text": "<p>You can use an extra value in the enum constant that can survive both name changes and resorting of the enums:</p>\n\n<pre><code>public enum MyEnum {\n MyFirstValue(10),\n MyFirstAndAHalfValue(15),\n MySecondValue(20);\n\n public int getId() {\n return id;\n }\n public static MyEnum of(int id) {\n for (MyEnum e : values()) {\n if (id == e.id) {\n return e;\n }\n }\n return null;\n }\n MyEnum(int id) {\n this.id = id;\n }\n private final int id;\n}\n</code></pre>\n\n<p>To get the id from the enum:</p>\n\n<pre><code>int id = MyFirstValue.getId();\n</code></pre>\n\n<p>To get the enum from an id:</p>\n\n<pre><code>MyEnum e = MyEnum.of(id);\n</code></pre>\n\n<p>I suggest using values with no meaning to avoid confusion if the enum names have to be changed.</p>\n\n<p>In the above example, I've used some variant of \"Basic row numbering\" leaving spaces so the numbers will likely stay in the same order as the enums.</p>\n\n<p>This version is faster than using a secondary table, but it makes the system more dependent on code and source code knowledge.</p>\n\n<p>To remedy that, you can set up a table with the enum ids in the database as well. Or go the other way and pick ids for the enums from a table as you add rows to it.</p>\n\n<p><strong>Sidenote</strong>: Always verify that you are not designing something that should be stored in a database table and maintained as a regular object though. If you can imagine that you have to add new constants to the enum at this point, when you are setting it up, that's an indication you may be better off creating a regular object and a table instead.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20298/"
] |
What is the best way to save enums into a database?
I know Java provides `name()` and `valueOf()` methods to convert enum values into a String and back. But are there any other (flexible) options to store these values?
Is there a smart way to make enums into unique numbers (`ordinal()` is not safe to use)?
#### Update
Thanks for all awesome and fast answers! It was as I suspected.
However, a note to [toolkit](https://stackoverflow.com/users/3295): That is one way. The problem is that I would have to add the same methods to each enum type that I create. That's a lot of duplicated code and, at the moment, Java does not support any solutions for this (a Java enum cannot extend other classes).
|
We *never* store enumerations as numerical ordinal values anymore; it makes debugging and support way too difficult. We store the actual enumeration value converted to string:
```
public enum Suit { Spade, Heart, Diamond, Club }
Suit theSuit = Suit.Heart;
szQuery = "INSERT INTO Customers (Name, Suit) " +
"VALUES ('Ian Boyd', %s)".format(theSuit.name());
```
and then read back with:
```
Suit theSuit = Suit.valueOf(reader["Suit"]);
```
The problem was in the past staring at Enterprise Manager and trying to decipher:
```
Name Suit
------------ ----
Kylie Guénin 2
Ian Boyd 1
```
verses
```
Name Suit
------------ -------
Kylie Guénin Diamond
Ian Boyd Heart
```
the latter is much easier. The former required getting at the source code and finding the numerical values that were assigned to the enumeration members.
Yes it takes more space, but the enumeration member names are short, and hard drives are cheap, and it is much more worth it to help when you're having a problem.
Additionally, if you use numerical values, you are tied to them. You cannot nicely insert or rearrange the members without having to force the old numerical values. For example, changing the Suit enumeration to:
```
public enum Suit { Unknown, Heart, Club, Diamond, Spade }
```
would have to become :
```
public enum Suit {
Unknown = 4,
Heart = 1,
Club = 3,
Diamond = 2,
Spade = 0 }
```
in order to maintain the legacy numerical values stored in the database.
How to sort them in the database
--------------------------------
The question comes up: lets say i wanted to order the values. Some people may want to sort them by the `enum`'s ordinal value. Of course, ordering the cards by the numerical value of the enumeration is meaningless:
```
SELECT Suit FROM Cards
ORDER BY SuitID; --where SuitID is integer value(4,1,3,2,0)
Suit
------
Spade
Heart
Diamond
Club
Unknown
```
That's not the order we want - we want them in enumeration order:
```
SELECT Suit FROM Cards
ORDER BY CASE SuitID OF
WHEN 4 THEN 0 --Unknown first
WHEN 1 THEN 1 --Heart
WHEN 3 THEN 2 --Club
WHEN 2 THEN 3 --Diamond
WHEN 0 THEN 4 --Spade
ELSE 999 END
```
The same work that is required if you save integer values is required if you save strings:
```
SELECT Suit FROM Cards
ORDER BY Suit; --where Suit is an enum name
Suit
-------
Club
Diamond
Heart
Spade
Unknown
```
But that's not the order we want - we want them in enumeration order:
```
SELECT Suit FROM Cards
ORDER BY CASE Suit OF
WHEN 'Unknown' THEN 0
WHEN 'Heart' THEN 1
WHEN 'Club' THEN 2
WHEN 'Diamond' THEN 3
WHEN 'Space' THEN 4
ELSE 999 END
```
My opinion is that this kind of ranking belongs in the user interface. If you are sorting items based on their enumeration value: you're doing something wrong.
But if you wanted to really do that, i would create a `Suits` [dimension table](https://en.wikipedia.org/wiki/Dimension_(data_warehouse)):
| Suit | SuitID | Rank | Color |
| --- | --- | --- | --- |
| Unknown | 4 | 0 | NULL |
| Heart | 1 | 1 | Red |
| Club | 3 | 2 | Black |
| Diamond | 2 | 3 | Red |
| Spade | 0 | 4 | Black |
This way, when you want to change your cards to use [***Kissing Kings* New Deck Order**](https://www.quora.com/When-you-buy-a-deck-of-cards-does-it-come-mixed-or-in-order) you can change it for display purposes without throwing away all your data:
| Suit | SuitID | Rank | Color | CardOrder |
| --- | --- | --- | --- | --- |
| Unknown | 4 | 0 | NULL | NULL |
| Spade | 0 | 1 | Black | 1 |
| Diamond | 2 | 2 | Red | 1 |
| Club | 3 | 3 | Black | -1 |
| Heart | 1 | 4 | Red | -1 |
Now we are separating an internal programming detail (enumeration name, enumeration value) with a display setting meant for users:
```
SELECT Cards.Suit
FROM Cards
INNER JOIN Suits ON Cards.Suit = Suits.Suit
ORDER BY Suits.Rank,
Card.Rank*Suits.CardOrder
```
|
229,865 |
<p>I have some simple .doc files I made in Word 2007 where I changed the text color and used highlights to compare some similar texts. What I'd like to do is change any instances of green text or gray highlighting to different respective colors for each.</p>
<p>I'm sure there is a simple way to do this with VBA but any other sort of answers are also welcome.</p>
<p>EDIT: While I do appreciate answers, one that allows me to keep the .doc files as .docs is preferred.</p>
|
[
{
"answer_id": 230305,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 1,
"selected": false,
"text": "<p>You can always save the file as HTML, and replace colors there. Color is represented with </p>\n\n<pre><code><span style='color:red'>...\n</code></pre>\n\n<p>and highlight is</p>\n\n<pre><code><span style='background:yellow;mso-highlight:yellow'>...\n</code></pre>\n\n<p>Should be easy to manipulate if your document is simple enough.</p>\n\n<p>Edit that answers the edit in the question: After you are done, re-open the file and save the file back as .doc.</p>\n"
},
{
"answer_id": 231736,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "<p>This is not from 2007, but the idea should suit. This example changes any current highlight to the new default highlight (wdBrightGreen) and any green text to red.</p>\n\n<pre><code>Sub ChangeColor\nOptions.DefaultHighlightColorIndex = wdBrightGreen\n\n Selection.Find.ClearFormatting\n Selection.Find.Highlight = True\n Selection.Find.Replacement.ClearFormatting\n Selection.Find.Replacement.Highlight = True\n Selection.Find.Execute Replace:=wdReplaceAll\n\n Selection.Find.ClearFormatting\n Selection.Find.Font.Color = wdColorBrightGreen\n Selection.Find.Replacement.ClearFormatting\n Selection.Find.Replacement.Font.Color = wdColorRed\n With Selection.Find\n .Text = \"\"\n .Replacement.Text = \"\"\n .Forward = True\n .Wrap = wdFindContinue\n End With\n Selection.Find.Execute Replace:=wdReplaceAll\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 595442,
"author": "guillermooo",
"author_id": 1670,
"author_profile": "https://Stackoverflow.com/users/1670",
"pm_score": 0,
"selected": false,
"text": "<p>This should work for your purpose:</p>\n\n<pre><code>Sub RehiliteAll()\n\n Const YOUR_REQUIRED_COLOR_IDX As Integer = 6 'RED'\n Dim doc As Range\n Set doc = ActiveDocument.Range\n\n With doc.Find\n .ClearFormatting 'resets default search options'\n .Highlight = True\n .Wrap = wdFindStop\n\n While .Execute\n\n If doc.HighlightColorIndex = YOUR_REQUIRED_COLOR_IDX Then\n doc.Select\n MsgBox doc.HighlightColorIndex\n 'Do stuff here'\n End If\n\n 'doc has been reassigned to the matching'\n 'range; we do this so word keeps searching'\n 'forward'\n doc.Collapse wdCollapseEnd\n Wend\n End With\n\n Set doc = Nothing\nEnd Sub\n\n'I am closing comment quotes so that SO formatting'\n'does not get messed up too much.'\n</code></pre>\n"
},
{
"answer_id": 9286663,
"author": "Bruce",
"author_id": 1210324,
"author_profile": "https://Stackoverflow.com/users/1210324",
"pm_score": 1,
"selected": false,
"text": "<p>I thought one could highlight a section of the coloured text and then choose \"select text with similar formatting\" option from the select text menu option on the Home tab. Then just select the text colour required.\nHope this works.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25680/"
] |
I have some simple .doc files I made in Word 2007 where I changed the text color and used highlights to compare some similar texts. What I'd like to do is change any instances of green text or gray highlighting to different respective colors for each.
I'm sure there is a simple way to do this with VBA but any other sort of answers are also welcome.
EDIT: While I do appreciate answers, one that allows me to keep the .doc files as .docs is preferred.
|
This is not from 2007, but the idea should suit. This example changes any current highlight to the new default highlight (wdBrightGreen) and any green text to red.
```
Sub ChangeColor
Options.DefaultHighlightColorIndex = wdBrightGreen
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.ClearFormatting
Selection.Find.Font.Color = wdColorBrightGreen
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Font.Color = wdColorRed
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
```
|
229,870 |
<p>I have a gridview containing some data from db, and after a check I want to see a small cross/tick image in each row, due to the result of the check.How can I change the image url dynamically? </p>
|
[
{
"answer_id": 251638,
"author": "gfrizzle",
"author_id": 23935,
"author_profile": "https://Stackoverflow.com/users/23935",
"pm_score": 0,
"selected": false,
"text": "<pre><code><Columns>\n <asp:TemplateField>\n <ItemTemplate>\n <asp:Image ID=\"check\" runat=\"server\" ImageUrl='<%#If(Eval(\"check\") = 1,\"images/checked.gif\",\"images/unchceked.gif\") %>' />\n </ItemTemplate>\n </asp:TemplateField>\n</Columns>\n</code></pre>\n"
},
{
"answer_id": 3689654,
"author": "Chinjoo",
"author_id": 356061,
"author_profile": "https://Stackoverflow.com/users/356061",
"pm_score": 2,
"selected": false,
"text": "<p>You could either use inline statement like <br/>\n<code><%#Eval(\"check\").ToString() == \"1\" ? \"images/checked.gif\" : \"images/unchceked.gif\")%></code></p>\n\n<p>or use a function to get the result as follows:</p>\n\n<pre><code><%# getImageUrl(Eval(\"value\")) %>\nPublic Function getImageUrl(ByVal value As Integer) As String\n If value = 0 Then\n Return \"images/unchceked.gif\"\n Else\n Return \"mages/checked.gif\"\n End If\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 4539324,
"author": "Beytan Kurt",
"author_id": 284420,
"author_profile": "https://Stackoverflow.com/users/284420",
"pm_score": 0,
"selected": false,
"text": "<p>in form:</p>\n\n<pre><code><Columns>\n <asp:TemplateField>\n <ItemTemplate>\n <asp:ImageButton ID=\"check\" runat=\"server\" ImageUrl='<%# GetImageUrl(Eval(\"Check\")) %>' />\n </ItemTemplate>\n </asp:TemplateField>\n</Columns>\n</code></pre>\n\n<p>code-behind:</p>\n\n<pre><code>public string GetImageUrl(object checkObject)\n{\n if (checkObject!= null)\n {\n bool check;\n bool parsable = bool.Parse(checkObject.ToString(), out check);\n check= parsable ? check : false;\n\n return check ? \"~/Media/Images/tick.png\" : \"~/Media/Images/untick.png\";\n }\n\n return \"~/Media/Images/none.png\";\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a gridview containing some data from db, and after a check I want to see a small cross/tick image in each row, due to the result of the check.How can I change the image url dynamically?
|
You could either use inline statement like
`<%#Eval("check").ToString() == "1" ? "images/checked.gif" : "images/unchceked.gif")%>`
or use a function to get the result as follows:
```
<%# getImageUrl(Eval("value")) %>
Public Function getImageUrl(ByVal value As Integer) As String
If value = 0 Then
Return "images/unchceked.gif"
Else
Return "mages/checked.gif"
End If
End Function
```
|
229,886 |
<p>I have heard mixed opinions over the amount of memory that a byte takes up in a java program.</p>
<p>I am aware you can store no more than +127 in a java byte, and the <a href="http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html" rel="noreferrer">documentation</a> says that a byte is only 8 bits but <a href="http://www.jguru.com/faq/view.jsp?EID=13647" rel="noreferrer">here</a> I am told that it actually takes up the same amount of memory as an int, and therefore is just a Type that helps in code comprehension and not efficiency. </p>
<p>Can anyone clear this up, and would this be an implementation specific issue?</p>
|
[
{
"answer_id": 229912,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<p>Java is never implementation or platform specific (at least as far as <a href=\"http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html\" rel=\"noreferrer\">primitive type sizes</a> are concerned). They primitive types are always guaranteed to stay the same no matter what platform you're on. This differs from (and was considered an improvement on) C and C++, where some of the primitive types were platform specific.</p>\n\n<p>Since it's faster for the underlying operating system to address four (or eight, in a 64-bit system) bytes at a time, the JVM may allocate more bytes to store a primitive byte, but you can still only store values from -128 to 127 in it.</p>\n"
},
{
"answer_id": 229917,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 2,
"selected": false,
"text": "<p>What you've been told is exactly right. The Java byte code specification only has 4-byte types and 8-byte types. </p>\n\n<p>byte, char, int, short, boolean, float are all stored in 4 bytes each.</p>\n\n<p>double and long are stored in 8 bytes.</p>\n\n<p>However byte code is only half the story. There's also the JVM, which is implementation-specific. There's enough info in Java byte code to determine that a variable was declared as a byte. A JVM implementor <em>may</em> decide to use only a byte, although I think that is highly unlikely.</p>\n"
},
{
"answer_id": 229921,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on how the JVM applies padding etc. An array of bytes will (in any sane system) be packed into 1-byte-per-element, but a class with four byte fields could either be tightly packed or padded onto word boundaries - it's implementation dependent.</p>\n"
},
{
"answer_id": 229949,
"author": "Christopher Lightfoot",
"author_id": 24525,
"author_profile": "https://Stackoverflow.com/users/24525",
"pm_score": 2,
"selected": false,
"text": "<p>You could always use longs and pack the data in yourself to increase efficiency. Then you can always gaurentee you'll be using all 4 bytes.</p>\n"
},
{
"answer_id": 229968,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 3,
"selected": false,
"text": "<p>A revealing exercise is to run <a href=\"http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javap.html\" rel=\"noreferrer\">javap</a> on some code that does simple things with bytes and ints. You'll see bytecodes that expect int parameters operating on bytes, and bytecodes being inserted to co-erce from one to another.</p>\n\n<p>Note though that arrays of bytes are not stored as arrays of 4-byte values, so a 1024-length byte array will use 1k of memory (Ignoring any overheads).</p>\n"
},
{
"answer_id": 229992,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, a byte variable in Java is in fact 4 bytes in memory. However this doesn't hold true for arrays. The storage of a byte array of 20 bytes is in fact only 20 bytes in memory. </p>\n\n<p>That is because the Java Bytecode Language only knows two integer number types: ints and longs. So it must handle all numbers internally as either type and these types are 4 and 8 bytes in memory.</p>\n\n<p>However, Java knows arrays with every integer number format. So the storage of short arrays is in fact two bytes per entry and one byte per entry for byte arrays.</p>\n\n<p>The reason why I keep saying \"the storage of\" is that an array is also an object in Java and every object requires multiple bytes of storage on its own, regardless of the storage that instance variables or the array storage in case of arrays require.</p>\n"
},
{
"answer_id": 230063,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p>Okay, there's been a lot of discussion and not a lot of code :)</p>\n\n<p>Here's a quick benchmark. It's got the normal caveats when it comes to this kind of thing - testing memory has oddities due to JITting etc, but with suitably large numbers it's useful anyway. It has two types, each with 80 members - LotsOfBytes has 80 bytes, LotsOfInts has 80 ints. We build lots of them, make sure they're not GC'd, and check memory usage:</p>\n\n<pre><code>class LotsOfBytes\n{\n byte a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;\n byte b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;\n byte c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;\n byte d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;\n byte e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;\n}\n\nclass LotsOfInts\n{\n int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;\n int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;\n int c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;\n int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;\n int e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;\n}\n\n\npublic class Test\n{\n private static final int SIZE = 1000000;\n\n public static void main(String[] args) throws Exception\n { \n LotsOfBytes[] first = new LotsOfBytes[SIZE];\n LotsOfInts[] second = new LotsOfInts[SIZE];\n\n System.gc();\n long startMem = getMemory();\n\n for (int i=0; i < SIZE; i++)\n {\n first[i] = new LotsOfBytes();\n }\n\n System.gc();\n long endMem = getMemory();\n\n System.out.println (\"Size for LotsOfBytes: \" + (endMem-startMem));\n System.out.println (\"Average size: \" + ((endMem-startMem) / ((double)SIZE)));\n\n System.gc();\n startMem = getMemory();\n for (int i=0; i < SIZE; i++)\n {\n second[i] = new LotsOfInts();\n }\n System.gc();\n endMem = getMemory();\n\n System.out.println (\"Size for LotsOfInts: \" + (endMem-startMem));\n System.out.println (\"Average size: \" + ((endMem-startMem) / ((double)SIZE)));\n\n // Make sure nothing gets collected\n long total = 0;\n for (int i=0; i < SIZE; i++)\n {\n total += first[i].a0 + second[i].a0;\n }\n System.out.println(total);\n }\n\n private static long getMemory()\n {\n Runtime runtime = Runtime.getRuntime();\n return runtime.totalMemory() - runtime.freeMemory();\n }\n}\n</code></pre>\n\n<p>Output on my box:</p>\n\n<pre><code>Size for LotsOfBytes: 88811688\nAverage size: 88.811688\nSize for LotsOfInts: 327076360\nAverage size: 327.07636\n0\n</code></pre>\n\n<p>So obviously there's some overhead - 8 bytes by the looks of it, although somehow only 7 for LotsOfInts (? like I said, there are oddities here) - but the point is that the byte fields appear to be packed in for LotsOfBytes such that it takes (after overhead removal) only a quarter as much memory as LotsOfInts.</p>\n"
},
{
"answer_id": 241302,
"author": "kohlerm",
"author_id": 26056,
"author_profile": "https://Stackoverflow.com/users/26056",
"pm_score": 2,
"selected": false,
"text": "<p>byte = 8bit = one byte defined by the Java Spec. </p>\n\n<p>how much memory an byte array needs is <strong>not</strong> defined by the Spec, nor is defined how much a complex objects needs. </p>\n\n<p>For the Sun JVM I documented the rules: <a href=\"https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/5163\" rel=\"nofollow noreferrer\">https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/5163</a></p>\n"
},
{
"answer_id": 242877,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>See my MonitoringTools at my site (www.csd.uoc.gr/~andreou)</p>\n\n<pre>\nclass X {\n byte b1, b2, b3...;\n}\n\nlong memoryUsed = MemoryMeasurer.measure(new X());\n</pre>\n\n<p>(It can be used for more complex objects/object graphs too)</p>\n\n<p>In Sun's 1.6 JDK, it seems that a byte indeed takes a single byte (in older versions, int ~ byte in terms of memory). But note that even in older versions, byte[] were also packed to one byte per entry.</p>\n\n<p>Anyway, the point is that there is no need for complex tests like Jon Skeet's above, that only give estimations. We can directly measure the size of an object!</p>\n"
},
{
"answer_id": 242892,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Reading through the above comments, it seems that my conclusion will come as a surprise to many (it is also a surprise to me), so it worths repeating:</p>\n\n<ul>\n<li><b>The old size(int) == size(byte) for variables holds no more</b>, at least in Sun's Java 6.</li>\n</ul>\n\n<p>Instead, size(byte) == 1 byte (!!)</p>\n"
},
{
"answer_id": 6941589,
"author": "Jeff Grigg",
"author_id": 409611,
"author_profile": "https://Stackoverflow.com/users/409611",
"pm_score": -1,
"selected": false,
"text": "<p>It appears that the answer is likely to depend on your JVM version and probably also the CPU architecture you're running on. The Intel line of CPUs do byte manipulation efficiently (due to its 8-bit CPU history). Some RISC chips require word (4 byte) alignment for many operations. And memory allocation can be different for variables on the stack, fields in a class, and in an array.</p>\n"
},
{
"answer_id": 11879948,
"author": "Unai Vivi",
"author_id": 1018783,
"author_profile": "https://Stackoverflow.com/users/1018783",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to point out that the statement</p>\n\n<p><em>you can store no more than +127 in a java byte</em></p>\n\n<p>is not truly correct.</p>\n\n<p>You can always store 256 different values in a byte, therefore you can easily have your 0..255 range as if it were an \"unsigned\" byte.</p>\n\n<p>It all depends on how you handle those 8 bits.</p>\n\n<p>Example:</p>\n\n<pre><code>byte B=(byte)200;//B contains 200\nSystem.out.println((B+256)%256);//Prints 200\nSystem.out.println(B&0xFF);//Prints 200\n</code></pre>\n"
},
{
"answer_id": 13898807,
"author": "Fuad Efendi",
"author_id": 1748983,
"author_profile": "https://Stackoverflow.com/users/1748983",
"pm_score": 3,
"selected": false,
"text": "<p>I did a test using <a href=\"http://code.google.com/p/memory-measurer/\" rel=\"noreferrer\">http://code.google.com/p/memory-measurer/</a>\nNote that I am using 64-bit Oracle/Sun Java 6, without any compression of references etc.</p>\n\n<p>Each object occupies some space, plus JVM needs to know address of that object, and \"address\" itself is 8 bytes.</p>\n\n<p>With primitives, looks like primitives are casted to 64-bit for better performance (of course!):</p>\n\n<pre><code>byte: 16 bytes,\n int: 16 bytes,\nlong: 24 bytes.\n</code></pre>\n\n<p>With Arrays:</p>\n\n<pre><code>byte[1]: 24 bytes\n int[1]: 24 bytes\nlong[1]: 24 bytes\n\nbyte[2]: 24 bytes\n int[2]: 24 bytes\nlong[2]: 32 bytes\n\nbyte[4]: 24 bytes\n int[4]: 32 bytes\nlong[4]: 48 bytes\n\nbyte[8]: 24 bytes => 8 bytes, \"start\" address, \"end\" address => 8 + 8 + 8 bytes\n int[8]: 48 bytes => 8 integers (4 bytes each), \"start\" address, \"end\" address => 8*4 + 8 + 8 bytes\nlong[8]: 80 bytes => 8 longs (8 bytes each), \"start\" address, \"end\" address => 8x8 + 8 + 8 bytes\n</code></pre>\n\n<p>And now guess what...</p>\n\n<pre><code> byte[8]: 24 bytes\n byte[1][8]: 48 bytes\n byte[64]: 80 bytes\n byte[8][8]: 240 bytes\n</code></pre>\n\n<p>P.S. Oracle Java 6, latest and greatest, 64-bit, 1.6.0_37, MacOS X</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29924/"
] |
I have heard mixed opinions over the amount of memory that a byte takes up in a java program.
I am aware you can store no more than +127 in a java byte, and the [documentation](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html) says that a byte is only 8 bits but [here](http://www.jguru.com/faq/view.jsp?EID=13647) I am told that it actually takes up the same amount of memory as an int, and therefore is just a Type that helps in code comprehension and not efficiency.
Can anyone clear this up, and would this be an implementation specific issue?
|
Okay, there's been a lot of discussion and not a lot of code :)
Here's a quick benchmark. It's got the normal caveats when it comes to this kind of thing - testing memory has oddities due to JITting etc, but with suitably large numbers it's useful anyway. It has two types, each with 80 members - LotsOfBytes has 80 bytes, LotsOfInts has 80 ints. We build lots of them, make sure they're not GC'd, and check memory usage:
```
class LotsOfBytes
{
byte a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
byte b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
byte c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
byte d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
byte e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;
}
class LotsOfInts
{
int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
int c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
int e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;
}
public class Test
{
private static final int SIZE = 1000000;
public static void main(String[] args) throws Exception
{
LotsOfBytes[] first = new LotsOfBytes[SIZE];
LotsOfInts[] second = new LotsOfInts[SIZE];
System.gc();
long startMem = getMemory();
for (int i=0; i < SIZE; i++)
{
first[i] = new LotsOfBytes();
}
System.gc();
long endMem = getMemory();
System.out.println ("Size for LotsOfBytes: " + (endMem-startMem));
System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));
System.gc();
startMem = getMemory();
for (int i=0; i < SIZE; i++)
{
second[i] = new LotsOfInts();
}
System.gc();
endMem = getMemory();
System.out.println ("Size for LotsOfInts: " + (endMem-startMem));
System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));
// Make sure nothing gets collected
long total = 0;
for (int i=0; i < SIZE; i++)
{
total += first[i].a0 + second[i].a0;
}
System.out.println(total);
}
private static long getMemory()
{
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
}
```
Output on my box:
```
Size for LotsOfBytes: 88811688
Average size: 88.811688
Size for LotsOfInts: 327076360
Average size: 327.07636
0
```
So obviously there's some overhead - 8 bytes by the looks of it, although somehow only 7 for LotsOfInts (? like I said, there are oddities here) - but the point is that the byte fields appear to be packed in for LotsOfBytes such that it takes (after overhead removal) only a quarter as much memory as LotsOfInts.
|
229,887 |
<p>Can a flash front end talk to a .net backend?</p>
|
[
{
"answer_id": 229901,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>Yes.</p>\n\n<p>We use <a href=\"http://www.adobe.com/products/flex/\" rel=\"nofollow noreferrer\">Adobe Flex</a> to talk to .Net XML web services.</p>\n\n<p>Be careful with complex serialised .Net types (for instance DataSets) - ActionScript can't handle them. </p>\n\n<p>Instead produce simple XML with primitive types.</p>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/44817\">Flex and ADO.NET Data Services...anyone done it?</a></p>\n\n<pre><code><mx:WebService id=\"myDataService\" showBusyCursor=\"true\">\n <mx:operation name=\"WebMethodName\" resultFormat=\"object\" result=\"functionFiredOnComplete();\"></mx:operation>\n</mx:WebService>\n\npublic function load():void\n{\n myDataService.loadWSDL( \"web method's wsdl\" );\n myDataService.WebMethodName.send( params );\n}\n\npublic function functionFiredOnComplete():void\n{ \n // get data\n var myData:Object = myDataService.WebMethodName.lastResult;\n ...\n</code></pre>\n"
},
{
"answer_id": 229908,
"author": "branchgabriel",
"author_id": 30807,
"author_profile": "https://Stackoverflow.com/users/30807",
"pm_score": 1,
"selected": false,
"text": "<p>Yes</p>\n\n<p>Best keywords to search for are Flash .net and Flex</p>\n\n<p>In the old days there was another tool but with Flex its all been simplified.</p>\n"
},
{
"answer_id": 229910,
"author": "bryanbcook",
"author_id": 30809,
"author_profile": "https://Stackoverflow.com/users/30809",
"pm_score": 2,
"selected": false,
"text": "<p>Flash can also talk to the hosting page via JavaScript.</p>\n"
},
{
"answer_id": 230050,
"author": "Steven Robbins",
"author_id": 26507,
"author_profile": "https://Stackoverflow.com/users/26507",
"pm_score": 1,
"selected": false,
"text": "<p>If you are de/serializing a lot of objects (which Flash/Flex isn't particularly fast at), or more complex types, then you might want to take a look at <a href=\"http://www.themidnightcoders.com/weborb/\" rel=\"nofollow noreferrer\">WebOrb</a>. It's a free object broker, which might sound scary, but it basically handles translation between the native object types of the two technologies. It pretty much \"just works\", and can increase performance quite significantly in some situations.</p>\n\n<p>It also comes with a code generation tool if all you want is CRUD and stored procedure access for a SQL database, which is quite nice.</p>\n"
},
{
"answer_id": 242931,
"author": "Ryan",
"author_id": 32009,
"author_profile": "https://Stackoverflow.com/users/32009",
"pm_score": 2,
"selected": false,
"text": "<p>you could also try AMF.NET, a .NET implementation of Flash Remoting using ActionScript Messaging Format (AMF)</p>\n\n<p><a href=\"http://amfnet.openmymind.net/overview/default.aspx\" rel=\"nofollow noreferrer\">http://amfnet.openmymind.net/overview/default.aspx</a></p>\n"
},
{
"answer_id": 697565,
"author": "Tjelle",
"author_id": 51839,
"author_profile": "https://Stackoverflow.com/users/51839",
"pm_score": 1,
"selected": false,
"text": "<p>I would recomend <a href=\"http://fluorinefx.net/docs/fluorine/index.html\" rel=\"nofollow noreferrer\">FluorineFX</a> we use that at work and its great. The only downside is that we end up with a lot of value objects that are only used to transfer data between .net and flex. And the fact that the standard C# naming style and the flex naming style has some minor differences makes value objects a bit ugly in either flex or .net.</p>\n"
},
{
"answer_id": 2335933,
"author": "Darth Perfidious",
"author_id": 100968,
"author_profile": "https://Stackoverflow.com/users/100968",
"pm_score": 0,
"selected": false,
"text": "<p>My older brother and I developed several methods for Flash/.Net communication. I've seen web services mentioned above (which is a great way of doing it), but we also used simple .aspx pages and had stuff passed via querystring (poor man's way of doing things), using Flashvars to get data TO Flash, but my favorite - Using .Net and a repeater control to build xml files which were then consumed by Flash. We created some pretty cool stuff doing that!</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Can a flash front end talk to a .net backend?
|
Yes.
We use [Adobe Flex](http://www.adobe.com/products/flex/) to talk to .Net XML web services.
Be careful with complex serialised .Net types (for instance DataSets) - ActionScript can't handle them.
Instead produce simple XML with primitive types.
See also: [Flex and ADO.NET Data Services...anyone done it?](https://stackoverflow.com/questions/44817)
```
<mx:WebService id="myDataService" showBusyCursor="true">
<mx:operation name="WebMethodName" resultFormat="object" result="functionFiredOnComplete();"></mx:operation>
</mx:WebService>
public function load():void
{
myDataService.loadWSDL( "web method's wsdl" );
myDataService.WebMethodName.send( params );
}
public function functionFiredOnComplete():void
{
// get data
var myData:Object = myDataService.WebMethodName.lastResult;
...
```
|
229,889 |
<p>What are the dangerous characters that should be replaced in user input when the users' input will be inserted in a MySQL query? I know about quotes, double quotes, \r and \n. Are there others?<br><sub>(I don't have the option of using a smart connector that accepts parameters so I have to build the query myself and this will be implemented in multiple programming languages, including some obscure ones so solutions such as <code>mysql_real_escape_string</code> in PHP are not valid)</sub></p>
|
[
{
"answer_id": 229941,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<p>What languages do you need to support? It is much better to use a language's built-in sanitization than to write your own.</p>\n\n<p>Edit: Looking at <a href=\"http://php.net/mysql_real_escape_string\" rel=\"nofollow noreferrer\"><code>mysql_real_escape_string</code></a> on php.net:</p>\n\n<blockquote>\n <p><code>mysql_real_escape_string()</code> calls MySQL's library function <code>mysql_real_escape_string</code>, which prepends backslashes to the following characters: <code>\\x00</code>, <code>\\n</code>, <code>\\r</code>, <code>\\</code>, <code>'</code>, <code>\"</code> and <code>\\x1a</code>.</p>\n</blockquote>\n"
},
{
"answer_id": 230209,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysql-real-escape-string.html\" rel=\"nofollow noreferrer\">mysql_real_escape_string()</a> from mysql.com docs:</p>\n\n<blockquote>\n <p><em>The string in from is encoded to an escaped SQL string, taking into account the current character set of the connection. The result is placed in to and a terminating null byte is appended. Characters encoded are NUL (ASCII 0), “\\n”, “\\r”, “\\”, “'”, “\"”, and Control-Z (see Section 8.1, “Literal Values”). (Strictly speaking, MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. This function quotes the other characters to make them easier to read in log files.)</em> </p>\n</blockquote>\n\n<hr>\n\n<p><strong>mysql_real_escape_string()</strong> is character set aware, so replicating all its abilities (especially against multi-byte attack issues) is not a small amount of work.</p>\n\n<p>From <a href=\"http://cognifty.com/blog.entry/id=6/addslashes_dont_call_it_a_comeback.html\" rel=\"nofollow noreferrer\">http://cognifty.com/blog.entry/id=6/addslashes_dont_call_it_a_comeback.html</a>:</p>\n\n<pre>\nAS = addslashes() \nMRES = mysql_real_escape_string()\nACS = addcslashes() //called with \"\\\\\\000\\n\\r'\\\"\\032%_\"\n\n<strong>Feature AS MRES ACS</strong>\nescapes quote, double quote, and backslash yes yes yes\nescapes LIKE modifiers: underscore, percent no no yes\nescapes with single quotes instead of backslash no yes*1 no\ncharacter-set aware no yes*2 no\nprevents multi-byte attacks no yes*3 no\n\n</pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26155/"
] |
What are the dangerous characters that should be replaced in user input when the users' input will be inserted in a MySQL query? I know about quotes, double quotes, \r and \n. Are there others?
(I don't have the option of using a smart connector that accepts parameters so I have to build the query myself and this will be implemented in multiple programming languages, including some obscure ones so solutions such as `mysql_real_escape_string` in PHP are not valid)
|
[mysql\_real\_escape\_string()](http://dev.mysql.com/doc/refman/5.0/en/mysql-real-escape-string.html) from mysql.com docs:
>
> *The string in from is encoded to an escaped SQL string, taking into account the current character set of the connection. The result is placed in to and a terminating null byte is appended. Characters encoded are NUL (ASCII 0), “\n”, “\r”, “\”, “'”, “"”, and Control-Z (see Section 8.1, “Literal Values”). (Strictly speaking, MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. This function quotes the other characters to make them easier to read in log files.)*
>
>
>
---
**mysql\_real\_escape\_string()** is character set aware, so replicating all its abilities (especially against multi-byte attack issues) is not a small amount of work.
From <http://cognifty.com/blog.entry/id=6/addslashes_dont_call_it_a_comeback.html>:
```
AS = addslashes()
MRES = mysql_real_escape_string()
ACS = addcslashes() //called with "\\\000\n\r'\"\032%_"
**Feature AS MRES ACS**
escapes quote, double quote, and backslash yes yes yes
escapes LIKE modifiers: underscore, percent no no yes
escapes with single quotes instead of backslash no yes*1 no
character-set aware no yes*2 no
prevents multi-byte attacks no yes*3 no
```
|
229,924 |
<p>What translation occurs when writing to a file that was opened in text mode that does not occur in binary mode? Specifically in MS Visual C.</p>
<pre><code>unsigned char buffer[256];
for (int i = 0; i < 256; i++) buffer[i]=i;
int size = 1;
int count = 256;
</code></pre>
<p>Binary mode:</p>
<pre><code>FILE *fp_binary = fopen(filename, "wb");
fwrite(buffer, size, count, fp_binary);
</code></pre>
<p>Versus text mode:</p>
<pre><code>FILE *fp_text = fopen(filename, "wt");
fwrite(buffer, size, count, fp_text);
</code></pre>
|
[
{
"answer_id": 229971,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 5,
"selected": false,
"text": "<p>In text mode, a newline \"\\n\" may be converted to a carriage return + newline \"\\r\\n\"</p>\n\n<p>Usually you'll want to open in binary mode. Trying to read any binary data in text mode won't work, it will be corrupted. You can read text ok in binary mode though - it just won't do automatic translations of \"\\n\" to \"\\r\\n\".</p>\n\n<p>See <a href=\"http://hostprogressive.com/support/php_5_docs/function.fopen.html\" rel=\"noreferrer\">fopen</a></p>\n"
},
{
"answer_id": 229995,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 3,
"selected": false,
"text": "<p>Additionally, when you fopen a file with \"rt\" the input is terminated on a Crtl-Z character.</p>\n"
},
{
"answer_id": 230655,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 2,
"selected": false,
"text": "<p>We had an interesting problem with opening files in text mode where the files had a mixture of line ending characters:</p>\n\n<pre><code>1\\n\\r\n2\\n\\r\n3\\n\n4\\n\\r\n5\\n\\r\n</code></pre>\n\n<p>Our requirement is that we can store our current position in the file (we used fgetpos), close the file and then later to reopen the file and seek to that position (we used fsetpos).</p>\n\n<p>However, where a file has mixtures of line endings then this process failed to seek to the actual same position. In our case (our tool parses C++), we were re-reading parts of the file we'd already seen.</p>\n\n<p>Go with binary - then you can control exactly what is read and written from the file.</p>\n"
},
{
"answer_id": 230878,
"author": "Jon Trauntvein",
"author_id": 19674,
"author_profile": "https://Stackoverflow.com/users/19674",
"pm_score": 7,
"selected": true,
"text": "<p>I believe that most platforms will ignore the \"t\" option or the \"text-mode\" option when dealing with streams. On windows, however, this is not the case. If you take a look at the description of the fopen() function at: <a href=\"http://msdn.microsoft.com/en-us/library/yeby3zcb(vs.71).aspx\" rel=\"noreferrer\">MSDN</a>, you will see that specifying the \"t\" option will have the following effect:</p>\n\n<ul>\n<li>line feeds ('\\n') will be translated to '\\r\\n\" sequences on output</li>\n<li>carriage return/line feed sequences will be translated to line feeds on input.</li>\n<li>If the file is opened in append mode, the end of the file will be examined for a ctrl-z character (character 26) and that character removed, if possible. It will also interpret the presence of that character as being the end of file. This is an unfortunate holdover from the days of CPM (something about the sins of the parents being visited upon their children up to the 3rd or 4th generation). Contrary to previously stated opinion, the ctrl-z character will not be appended.</li>\n</ul>\n"
},
{
"answer_id": 24798837,
"author": "Ming",
"author_id": 2021245,
"author_profile": "https://Stackoverflow.com/users/2021245",
"pm_score": 3,
"selected": false,
"text": "<p>Another difference is when using <code>fseek</code></p>\n<blockquote>\n<p>If the stream is open in binary mode, the new position is exactly offset bytes measured from the beginning of the file if origin is SEEK_SET, from the current file position if origin is SEEK_CUR, and from the end of the file if origin is SEEK_END. Some binary streams may not support the SEEK_END.</p>\n<p>If the stream is open in text mode, the only supported values for offset are zero (which works with any origin) and a value returned by an earlier call to std::ftell on a stream associated with the same file (which only works with origin of SEEK_SET.</p>\n</blockquote>\n"
},
{
"answer_id": 58777193,
"author": "Ajith Kumat",
"author_id": 8609506,
"author_profile": "https://Stackoverflow.com/users/8609506",
"pm_score": 0,
"selected": false,
"text": "<p>In 'w' mode, the file is opened in write mode and the basic coding is 'utf-8' \nin 'wb' mode, the file is opened in write -binary mode and it is resposible for writing other special characters and the encoding may be 'utf-16le' or others </p>\n"
},
{
"answer_id": 64306464,
"author": "David Lopez",
"author_id": 4044001,
"author_profile": "https://Stackoverflow.com/users/4044001",
"pm_score": 2,
"selected": false,
"text": "<p>Even though this question was already answered and clearly explained, I think it would be interesting to show the main issue (translation between \\n and \\r\\n) with a simple code example. Note that I'm not addressing the issue of the Crtl-Z character at the end of the file.</p>\n<pre><code>#include <stdio.h>\n#include <string.h>\n\nint main() {\n FILE *f;\n char string[] = "A\\nB";\n int len;\n \n len = strlen(string);\n printf("As you'd expect string has %d characters... ", len); /* prints 3*/\n f = fopen("test.txt", "w"); /* Text mode */\n fwrite(string, 1, len, f); /* On windows "A\\r\\nB" is writen */\n printf ("but %ld bytes were writen to file", ftell(f)); /* prints 4 on Windows, 3 on Linux*/ \n fclose(f);\n return 0;\n}\n</code></pre>\n<p>If you execute the program on Windows, you will see the following message printed:</p>\n<pre><code>As you'd expect string has 3 characters... but 4 bytes were writen to file\n</code></pre>\n<p>Of course you can also open the file with a text editor like Notepad++ and see yourself the characters:</p>\n<p><a href=\"https://i.stack.imgur.com/p3uAB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/p3uAB.png\" alt=\"enter image description here\" /></a></p>\n<p>The inverse conversion is performed on Windows when reading the file in text mode.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5065/"
] |
What translation occurs when writing to a file that was opened in text mode that does not occur in binary mode? Specifically in MS Visual C.
```
unsigned char buffer[256];
for (int i = 0; i < 256; i++) buffer[i]=i;
int size = 1;
int count = 256;
```
Binary mode:
```
FILE *fp_binary = fopen(filename, "wb");
fwrite(buffer, size, count, fp_binary);
```
Versus text mode:
```
FILE *fp_text = fopen(filename, "wt");
fwrite(buffer, size, count, fp_text);
```
|
I believe that most platforms will ignore the "t" option or the "text-mode" option when dealing with streams. On windows, however, this is not the case. If you take a look at the description of the fopen() function at: [MSDN](http://msdn.microsoft.com/en-us/library/yeby3zcb(vs.71).aspx), you will see that specifying the "t" option will have the following effect:
* line feeds ('\n') will be translated to '\r\n" sequences on output
* carriage return/line feed sequences will be translated to line feeds on input.
* If the file is opened in append mode, the end of the file will be examined for a ctrl-z character (character 26) and that character removed, if possible. It will also interpret the presence of that character as being the end of file. This is an unfortunate holdover from the days of CPM (something about the sins of the parents being visited upon their children up to the 3rd or 4th generation). Contrary to previously stated opinion, the ctrl-z character will not be appended.
|
229,925 |
<p>Using the following code I get a nice formatted string:</p>
<pre><code>Request.QueryString.ToString
</code></pre>
<p>Gives me something like: &hello=world&microsoft=sucks</p>
<p>But when I use this code to clone the collection to another object (of the same type) I get the Type() back from the ToString() method instead.</p>
<pre><code>System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
variables.Remove("sid");
Response.Write(variables.ToString());
</code></pre>
<p>Is there a tidier way to output it rather than looking and building the string manually?</p>
|
[
{
"answer_id": 229964,
"author": "Johannes Hädrich",
"author_id": 18246,
"author_profile": "https://Stackoverflow.com/users/18246",
"pm_score": 2,
"selected": false,
"text": "<p>Why do you want to copy the QueryString collection into a new NameValueCollection?</p>\n\n<pre><code> if (!string.IsNullOrEmpty(Request.QueryString[\"sid\"]))\n Request.QueryString.Remove(\"sid\");\n</code></pre>\n\n<p>Yes indeed, i am wrong, it is read only. So the essence is to use the Remove Method on your NameValuecollection:</p>\n\n<pre><code>System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);\nif (!string.IsNullOrEmpty(variables[\"sid\"]))\n variables.Remove(\"sid\");\n</code></pre>\n"
},
{
"answer_id": 229969,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>Request.QueryString actually return a HttpValueCollection object (which unfortuately, is internal to System.Web so you can't you it). </p>\n\n<p>Nevertheless, HttpValueCollection is derived from NameValueCollection, and it's Remove() method remains intact, so you should be able to call Request.QueryString.Remove(\"sid\");</p>\n"
},
{
"answer_id": 229976,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 2,
"selected": false,
"text": "<p>Because it is actually a special NVC that is of type HTTPValueCollection.\nSo when you call .ToString on it, it knows how to format it correctly.</p>\n"
},
{
"answer_id": 229991,
"author": "Igal Tabachnik",
"author_id": 8205,
"author_profile": "https://Stackoverflow.com/users/8205",
"pm_score": 4,
"selected": true,
"text": "<p>You can also use Reflector to extract the <code>HttpValueCollection</code> class into your own, and use it then.</p>\n"
},
{
"answer_id": 230092,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't absolutely need a NameValueCollection, A dictionary offers a lot of the same semantics: </p>\n\n<pre><code>var variables = Request.QueryString.OfType<DictionaryEntry>()\n .Where(entry => entry.Key != \"sid\")\n .ToDictionary(entry => entry.Key, entry => entry.Value);\n</code></pre>\n"
},
{
"answer_id": 1425729,
"author": "Michele Bersini",
"author_id": 173568,
"author_profile": "https://Stackoverflow.com/users/173568",
"pm_score": 6,
"selected": false,
"text": "<p>HttpValueCollection is internal, but you can use \"var\" to declare it without extract it with reflector.</p>\n\n<pre><code>var query = HttpUtility.ParseQueryString(Request.Url.Query);\nquery[\"Lang\"] = myLanguage; // Add or replace param\nstring myNewUrl = Request.Url.AbsolutePath + \"?\" + query;\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258/"
] |
Using the following code I get a nice formatted string:
```
Request.QueryString.ToString
```
Gives me something like: &hello=worldµsoft=sucks
But when I use this code to clone the collection to another object (of the same type) I get the Type() back from the ToString() method instead.
```
System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
variables.Remove("sid");
Response.Write(variables.ToString());
```
Is there a tidier way to output it rather than looking and building the string manually?
|
You can also use Reflector to extract the `HttpValueCollection` class into your own, and use it then.
|
229,935 |
<p>OK, first for context look at the Windows desktop; You can take items (folders, files) on the desktop and drag them around to different places and they "stay" where you dragged them. This seems to be a pretty useful feature to offer users so as to allow them to create their own "groupings" of items.</p>
<p>My question is thus:
Is there a control in .NET that approximates this behavior with a collection of items?</p>
<p>I'm thinking something like a listview in "LargeIcon" mode, but it allows you to drag the icons around to different places inside the control.</p>
|
[
{
"answer_id": 229982,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I think the closest would the ListView control, but even that is more like an explorer window. You might be able to create your own view that does what you want, but you'd need to manually persist icon locations somewhere.</p>\n"
},
{
"answer_id": 230115,
"author": "Totty",
"author_id": 30838,
"author_profile": "https://Stackoverflow.com/users/30838",
"pm_score": 1,
"selected": false,
"text": "<p>If you are not opposed to using WPF, Josh Smith has created a pretty neat canvas that I am currently using for a project. It allows you to add controls and drag them around the canvas. You would have to handle what is loaded on the canvas and where on the next load of the program, but that is pretty simple.\n<a href=\"http://www.codeproject.com/KB/WPF/DraggingElementsInCanvas.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/WPF/DraggingElementsInCanvas.aspx</a></p>\n"
},
{
"answer_id": 230121,
"author": "Haydar",
"author_id": 288,
"author_profile": "https://Stackoverflow.com/users/288",
"pm_score": 1,
"selected": false,
"text": "<p>This depends on whether this is a windows application or a web browser based application. In either case you need to have some sort of container to manage the locations of controls. You can manage the position of controls inside of a container with their X and Y coordinates. </p>\n\n<p>You would handle the actual movement using the drag events. So you have drag start, while dragging (you might show a place holder graphic or change the cursor), and finally a drag end (set the control's x and y to the new position). Obviously these aren't the actual event names, but a search for \"how to handle drag events\" should get you started.</p>\n\n<p>In a web environment, I know jquery has dragging capability built in. So you might want to look at that. The one big thing you'll have to be careful of is maintaining the positions of your controls between postbacks. I'm not sure what would happen in this case.</p>\n"
},
{
"answer_id": 231486,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 4,
"selected": true,
"text": "<p>You can do this with a standard ListView control by implementing drag-and-drop. Here's a sample control that does this:</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class MyListView : ListView {\n private Point mItemStartPos;\n private Point mMouseStartPos;\n\n public MyListView() {\n this.AllowDrop = true;\n this.View = View.LargeIcon;\n this.AutoArrange = false;\n this.DoubleBuffered = true;\n }\n\n protected override void OnDragEnter(DragEventArgs e) {\n if (e.Data.GetData(typeof(ListViewItem)) != null) e.Effect = DragDropEffects.Move;\n }\n protected override void OnItemDrag(ItemDragEventArgs e) {\n // Start dragging\n ListViewItem item = e.Item as ListViewItem;\n mItemStartPos = item.Position;\n mMouseStartPos = Control.MousePosition;\n this.DoDragDrop(item, DragDropEffects.Move);\n }\n protected override void OnDragOver(DragEventArgs e) {\n // Move icon\n ListViewItem item = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;\n if (item != null) {\n Point mousePos = Control.MousePosition;\n item.Position = new Point(mItemStartPos.X + mousePos.X - mMouseStartPos.X,\n mItemStartPos.Y + mousePos.Y - mMouseStartPos.Y);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 37005844,
"author": "Ledom",
"author_id": 5098871,
"author_profile": "https://Stackoverflow.com/users/5098871",
"pm_score": 0,
"selected": false,
"text": "<p>Windows uses <code>ListView32</code>, an internal control with drag n' drop placeholder features, custom borders...</p>\n\n<p>The icon location can be stored in a XML file, or in the application settings (by putting the XML as string and converting it to file when needed).</p>\n\n<p>You can do, for example:</p>\n\n<pre><code><icons>\n <icon1>\n <name>Icon1</name>\n <text>My PC</text>\n <imageIndex>16</imageIndex>\n </icon1>\n <icon2>\n .....\n </icon2> \n .....\n</icons>\n</code></pre>\n\n<p>Lorenzo</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13776/"
] |
OK, first for context look at the Windows desktop; You can take items (folders, files) on the desktop and drag them around to different places and they "stay" where you dragged them. This seems to be a pretty useful feature to offer users so as to allow them to create their own "groupings" of items.
My question is thus:
Is there a control in .NET that approximates this behavior with a collection of items?
I'm thinking something like a listview in "LargeIcon" mode, but it allows you to drag the icons around to different places inside the control.
|
You can do this with a standard ListView control by implementing drag-and-drop. Here's a sample control that does this:
```
using System;
using System.Drawing;
using System.Windows.Forms;
public class MyListView : ListView {
private Point mItemStartPos;
private Point mMouseStartPos;
public MyListView() {
this.AllowDrop = true;
this.View = View.LargeIcon;
this.AutoArrange = false;
this.DoubleBuffered = true;
}
protected override void OnDragEnter(DragEventArgs e) {
if (e.Data.GetData(typeof(ListViewItem)) != null) e.Effect = DragDropEffects.Move;
}
protected override void OnItemDrag(ItemDragEventArgs e) {
// Start dragging
ListViewItem item = e.Item as ListViewItem;
mItemStartPos = item.Position;
mMouseStartPos = Control.MousePosition;
this.DoDragDrop(item, DragDropEffects.Move);
}
protected override void OnDragOver(DragEventArgs e) {
// Move icon
ListViewItem item = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;
if (item != null) {
Point mousePos = Control.MousePosition;
item.Position = new Point(mItemStartPos.X + mousePos.X - mMouseStartPos.X,
mItemStartPos.Y + mousePos.Y - mMouseStartPos.Y);
}
}
}
```
|
229,944 |
<p>I have a search box that doesn't have a submit button, I need to be able to hit enter and then execute a method, how do I do this?</p>
|
[
{
"answer_id": 229958,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "<p>Use the TextChanged event, and set the AutoPostBack property to true.</p>\n"
},
{
"answer_id": 230345,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>You could add a hidden button to the page and wire-up your method to that button's click event. Then add a small bit of javascript to trigger that button's postback action when you press enter inside the textbox.</p>\n\n<pre><code>this.myTextBox.Attributes.Add(\n \"onkeydown\", \n \"return keyDownHandler(13, 'javascript:\" \n + this.Page.ClientScript.GetPostBackEventReference(this.myButton, string.Empty).Replace(\"'\", \"%27\") \n + \"', event);\");\n</code></pre>\n\n<p>(You could also replace the hard-coded 13 with <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx\" rel=\"nofollow noreferrer\">Windows.Forms.Keys</a>.Enter, if you'd prefer an easier to read version.)</p>\n\n<p>Where keyDownHandler is a JavaScript function like this:</p>\n\n<pre><code>function keyDownHandler(iKeyCode, sFunc, e) { \n if (e == null) { \n e = window.event; \n } \n if (e.keyCode == iKeyCode) { \n eval(unescape(sFunc)); return false; \n } \n}\n</code></pre>\n\n<p>Note, this is based on the implementation of <a href=\"http://www.dotnetnuke.com/\" rel=\"nofollow noreferrer\">DotNetNuke</a>'s <a href=\"http://www.dotnetnuke.com/Products/Development/Forge/ComponentClientAPI/tabid/851/Default.aspx\" rel=\"nofollow noreferrer\">ClientAPI web utility</a>.</p>\n"
},
{
"answer_id": 230379,
"author": "Max Schilling",
"author_id": 29662,
"author_profile": "https://Stackoverflow.com/users/29662",
"pm_score": 3,
"selected": true,
"text": "<p>you could also do something simple like this with CSS:</p>\n\n<pre><code><asp:Panel DefaultButton=\"myButton\" runat=\"server\">\n <asp:TextBox ID=\"myTextBox\" runat=\"server\" />\n <asp:Button ID=\"myButton\" runat=\"server\" onclick=\"myButton_Click\" style=\"display: none; \" />\n</asp:Panel>\n</code></pre>\n\n<p>The panel may or may not be necessary depending on your implementation and surrounding controls, but this works and does a postback for me.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29445/"
] |
I have a search box that doesn't have a submit button, I need to be able to hit enter and then execute a method, how do I do this?
|
you could also do something simple like this with CSS:
```
<asp:Panel DefaultButton="myButton" runat="server">
<asp:TextBox ID="myTextBox" runat="server" />
<asp:Button ID="myButton" runat="server" onclick="myButton_Click" style="display: none; " />
</asp:Panel>
```
The panel may or may not be necessary depending on your implementation and surrounding controls, but this works and does a postback for me.
|
229,959 |
<p>This question is related to a previous post of mine <a href="https://stackoverflow.com/questions/227225/is-injecting-dao-into-entities-a-bad-thing">Here</a>. Basically, I want to inject a DAO into an entity i.e. </p>
<pre><code>public class User
{
IUserDAO userDAO;
public User()
{
userDAO = IoCContainer.Resolve<IUserDAO>;
}
public User(IUserDAO userDAO)
{
this.userDAO = userDAO;
}
//Wrapped DAO methods i.e
public User Save()
{
return userDAO.Save(this);
}
}
</code></pre>
<p>Here if I had a custom methods in my DAO then I basically have to wrap them in the entity object. So if I had a IUserDAO.Register() I would then have to create a User.Register() method to wrap it. </p>
<p>What would be better is to create a proxy object where the methods from the DAO are dynamically assign to the User object. So I may have something that looks like this:</p>
<pre><code>var User = DAOProxyService.Create(new User());
User.Save();
</code></pre>
<p>This would mean that I can keep the User entity as a pretty dumb class suitable for data transfer over the wire, but also magically give it a bunch of DAO methods.</p>
<p>This is very much out of my confort zone though, and I wondered what I would need to accomplish this? Could I use Castles Dynamic proxy? Also would the C# compiler be able to cope with this and know about the dynamically added methods? </p>
<p>Feel free to let me know if this is nonsense. </p>
<p>EDIT:</p>
<blockquote>
<p>What we need to do it somehow declare DAOProxyService.Create() as returning a User object -- at compile time. This can be done with generics.</p>
</blockquote>
<p>This isnt quite true, what I want to return isn't a User object but a User object with dynamically added UserDAO methods. As this class isn't defnied anywhere the compiler will not know what to make of it. </p>
<p>What I am essentially returning is a new object that looks like: User : IUserDAO, so I guess I could cast as required. But this seems messy. </p>
<p>Looks like what I am looking for is similar to this: <a href="http://www.almostserio.us/articles/2005/01/12/mixins-using-castle-dynamicproxy" rel="nofollow noreferrer">Mixins</a></p>
|
[
{
"answer_id": 229958,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "<p>Use the TextChanged event, and set the AutoPostBack property to true.</p>\n"
},
{
"answer_id": 230345,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>You could add a hidden button to the page and wire-up your method to that button's click event. Then add a small bit of javascript to trigger that button's postback action when you press enter inside the textbox.</p>\n\n<pre><code>this.myTextBox.Attributes.Add(\n \"onkeydown\", \n \"return keyDownHandler(13, 'javascript:\" \n + this.Page.ClientScript.GetPostBackEventReference(this.myButton, string.Empty).Replace(\"'\", \"%27\") \n + \"', event);\");\n</code></pre>\n\n<p>(You could also replace the hard-coded 13 with <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx\" rel=\"nofollow noreferrer\">Windows.Forms.Keys</a>.Enter, if you'd prefer an easier to read version.)</p>\n\n<p>Where keyDownHandler is a JavaScript function like this:</p>\n\n<pre><code>function keyDownHandler(iKeyCode, sFunc, e) { \n if (e == null) { \n e = window.event; \n } \n if (e.keyCode == iKeyCode) { \n eval(unescape(sFunc)); return false; \n } \n}\n</code></pre>\n\n<p>Note, this is based on the implementation of <a href=\"http://www.dotnetnuke.com/\" rel=\"nofollow noreferrer\">DotNetNuke</a>'s <a href=\"http://www.dotnetnuke.com/Products/Development/Forge/ComponentClientAPI/tabid/851/Default.aspx\" rel=\"nofollow noreferrer\">ClientAPI web utility</a>.</p>\n"
},
{
"answer_id": 230379,
"author": "Max Schilling",
"author_id": 29662,
"author_profile": "https://Stackoverflow.com/users/29662",
"pm_score": 3,
"selected": true,
"text": "<p>you could also do something simple like this with CSS:</p>\n\n<pre><code><asp:Panel DefaultButton=\"myButton\" runat=\"server\">\n <asp:TextBox ID=\"myTextBox\" runat=\"server\" />\n <asp:Button ID=\"myButton\" runat=\"server\" onclick=\"myButton_Click\" style=\"display: none; \" />\n</asp:Panel>\n</code></pre>\n\n<p>The panel may or may not be necessary depending on your implementation and surrounding controls, but this works and does a postback for me.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425/"
] |
This question is related to a previous post of mine [Here](https://stackoverflow.com/questions/227225/is-injecting-dao-into-entities-a-bad-thing). Basically, I want to inject a DAO into an entity i.e.
```
public class User
{
IUserDAO userDAO;
public User()
{
userDAO = IoCContainer.Resolve<IUserDAO>;
}
public User(IUserDAO userDAO)
{
this.userDAO = userDAO;
}
//Wrapped DAO methods i.e
public User Save()
{
return userDAO.Save(this);
}
}
```
Here if I had a custom methods in my DAO then I basically have to wrap them in the entity object. So if I had a IUserDAO.Register() I would then have to create a User.Register() method to wrap it.
What would be better is to create a proxy object where the methods from the DAO are dynamically assign to the User object. So I may have something that looks like this:
```
var User = DAOProxyService.Create(new User());
User.Save();
```
This would mean that I can keep the User entity as a pretty dumb class suitable for data transfer over the wire, but also magically give it a bunch of DAO methods.
This is very much out of my confort zone though, and I wondered what I would need to accomplish this? Could I use Castles Dynamic proxy? Also would the C# compiler be able to cope with this and know about the dynamically added methods?
Feel free to let me know if this is nonsense.
EDIT:
>
> What we need to do it somehow declare DAOProxyService.Create() as returning a User object -- at compile time. This can be done with generics.
>
>
>
This isnt quite true, what I want to return isn't a User object but a User object with dynamically added UserDAO methods. As this class isn't defnied anywhere the compiler will not know what to make of it.
What I am essentially returning is a new object that looks like: User : IUserDAO, so I guess I could cast as required. But this seems messy.
Looks like what I am looking for is similar to this: [Mixins](http://www.almostserio.us/articles/2005/01/12/mixins-using-castle-dynamicproxy)
|
you could also do something simple like this with CSS:
```
<asp:Panel DefaultButton="myButton" runat="server">
<asp:TextBox ID="myTextBox" runat="server" />
<asp:Button ID="myButton" runat="server" onclick="myButton_Click" style="display: none; " />
</asp:Panel>
```
The panel may or may not be necessary depending on your implementation and surrounding controls, but this works and does a postback for me.
|
229,998 |
<p>I want to copy all of the columns of a row, but not have to specify every column. I am aware of the syntax at <a href="http://dev.mysql.com/doc/refman/5.1/en/insert-select.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/insert-select.html</a> but I see no way to ignore a column.</p>
<p>For my example, I am trying to copy all the columns of a row to a new row, except for the primary key.</p>
<p>Is there a way to do that without having to write the query with every field in it?</p>
|
[
{
"answer_id": 230009,
"author": "Josh Bush",
"author_id": 1672,
"author_profile": "https://Stackoverflow.com/users/1672",
"pm_score": 2,
"selected": false,
"text": "<p>You'll need to list out the columns that you want to select if you aren't selecting them all. Copy/Paste is your friend.</p>\n"
},
{
"answer_id": 230018,
"author": "Eric Lamb",
"author_id": 538,
"author_profile": "https://Stackoverflow.com/users/538",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't specify the columns you have to keep the entries in order. For example:</p>\n\n<pre><code>INSERT INTO `users` (`ID`, `Email`, `UserName`) VALUES\n(1, '[email protected]', 'StackOverflow')\n</code></pre>\n\n<p>Would work but</p>\n\n<pre><code>INSERT INTO `users` VALUES\n('[email protected]', 'StackOverflow')\n</code></pre>\n\n<p>would place the Email at the ID column so it's no good.</p>\n\n<p>Try writing the columns once like:</p>\n\n<pre><code>INSERT INTO `users` (`Email`, `UserName`) VALUES\n('[email protected]', 'StackOverflow'),\n('[email protected]', 'StackOverflow2'),\n('[email protected]', 'StackOverflow3'),\netc...\n</code></pre>\n\n<p>I think there's a limit to how many rows you can insert with that method though.</p>\n"
},
{
"answer_id": 230061,
"author": "Mischa Kroon",
"author_id": 30600,
"author_profile": "https://Stackoverflow.com/users/30600",
"pm_score": 1,
"selected": false,
"text": "<p>No, this isn't possible. </p>\n\n<p>But it's easy to get the column list and just delete which one you don't want copied this process can also be done through code etc. </p>\n"
},
{
"answer_id": 668060,
"author": "Dipin",
"author_id": 67976,
"author_profile": "https://Stackoverflow.com/users/67976",
"pm_score": 0,
"selected": false,
"text": "<p>I'm assuming that since you want to omit the primary key that it is an <code>auto_increment</code> column and you want MySQL to autogenerate the next value in the sequence.</p>\n\n<p>Given that, assuming that you do not need to do bulk inserts via the insert into ... select from method, the following will work for single/multi record inserts:</p>\n\n<p>insert into mytable (null, 'a', 'b', 'c');</p>\n\n<p>Where the first column is your <code>auto_incremented</code> primary key and the others are your other columns on the table. When MySQL sees a null (or 0) for an <code>auto_incremented</code> column it will automatically replace the null with the next valid value (see <a href=\"http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_no_auto_value_on_zero\" rel=\"nofollow noreferrer\">this link</a> for more information). This functionality can be disabled by disabling the <code>NO_AUTO_VALUE_ON_ZERO</code> sql mode described in that link.</p>\n\n<p>Let me know if you have any questions.</p>\n\n<p>-Dipin</p>\n"
},
{
"answer_id": 3918543,
"author": "Lore",
"author_id": 473777,
"author_profile": "https://Stackoverflow.com/users/473777",
"pm_score": 4,
"selected": false,
"text": "<p>If your <code>id</code> or primary key column is an <code>auto_increment</code> you can use a temp table:</p>\n\n<pre><code>CREATE TEMPORARY TABLE temp_table \nAS \nSELECT * FROM source_table WHERE id='7'; \nUPDATE temp_table SET id='100' WHERE id='7';\nINSERT INTO source_table SELECT * FROM temp_table;\nDROP TEMPORARY TABLE temp_table;\n</code></pre>\n\n<p>so in this way you can copy all data in row id='7' and then assign\nnew value '100' (or whatever value falls above the range of your current auto_increment value in source_table).</p>\n\n<p>Edit: Mind the ; after the statments :)</p>\n"
},
{
"answer_id": 6309476,
"author": "Casey",
"author_id": 793083,
"author_profile": "https://Stackoverflow.com/users/793083",
"pm_score": 2,
"selected": false,
"text": "<p>This is a PHP script that I wrote to do this, it will assume that your first col is your auto increment.</p>\n\n<pre><code>$sql = \"SELECT * FROM table_name LIMIT 1\"; \n$res = mysql_query($sql) or die(mysql_error());\nfor ($i = 1; $i < mysql_num_fields($res); $i++) {\n $col_names .= mysql_field_name($res, $i).\", \";\n }\n $col_names = substr($col_names, 0, -2);\n\n$sql = \"INSERT INTO table_name (\".$col_names.\") SELECT \".$col_names.\" FROM table_name WHERE condition \";\n$res = mysql_query($sql) or die(mysql_error());\n</code></pre>\n"
},
{
"answer_id": 8484692,
"author": "Jamie Williamson",
"author_id": 1095080,
"author_profile": "https://Stackoverflow.com/users/1095080",
"pm_score": 1,
"selected": false,
"text": "<p>Copy the table to a new one, then delete the column you don't want. Simple. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to copy all of the columns of a row, but not have to specify every column. I am aware of the syntax at <http://dev.mysql.com/doc/refman/5.1/en/insert-select.html> but I see no way to ignore a column.
For my example, I am trying to copy all the columns of a row to a new row, except for the primary key.
Is there a way to do that without having to write the query with every field in it?
|
If your `id` or primary key column is an `auto_increment` you can use a temp table:
```
CREATE TEMPORARY TABLE temp_table
AS
SELECT * FROM source_table WHERE id='7';
UPDATE temp_table SET id='100' WHERE id='7';
INSERT INTO source_table SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
```
so in this way you can copy all data in row id='7' and then assign
new value '100' (or whatever value falls above the range of your current auto\_increment value in source\_table).
Edit: Mind the ; after the statments :)
|
230,014 |
<p>I'm using the ASP.NET 3.5 SP1 System.Web.Routing with classic WebForms, as described in <a href="http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/" rel="noreferrer">http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/</a></p>
<p><strong>All works fine</strong>, I have custom SEO urls and even the postback works. <strong>But there is a case where the postback always fails</strong> and I get a:</p>
<p><em>Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.</em></p>
<p>Here is the scenario to reproduce the error:</p>
<ol>
<li>Create a standard webform mypage.aspx with a button</li>
<li>Create a Route that maps "a/b/{id}" to "~/mypage.aspx"</li>
<li>When you execute the site, you can navigate <a href="http://localhost:XXXX/a/b/something" rel="noreferrer">http://localhost:XXXX/a/b/something</a> the page works. But when you press the button you get the error. The error doen't happen when the Route is just "a/{id}". </li>
</ol>
<p>It seems to be related to the number of sub-paths in the url. If there are at least 2 sub-paths the viewstate validation fails.</p>
<p>You get the error even with EnableViewStateMac="false".</p>
<p>Any ideas? Is it a bug?</p>
<p>Thanks</p>
|
[
{
"answer_id": 230022,
"author": "Mischa Kroon",
"author_id": 30600,
"author_profile": "https://Stackoverflow.com/users/30600",
"pm_score": -1,
"selected": false,
"text": "<p>Are you using safari as a browser? if so then this will probably be a problem with a large float. Remove that float and things will work fine. </p>\n"
},
{
"answer_id": 307768,
"author": "JSmyth",
"author_id": 54794,
"author_profile": "https://Stackoverflow.com/users/54794",
"pm_score": 0,
"selected": false,
"text": "<p>I had this same issue,\nI had some rogue</p>\n\n<pre><code><form></form>\n</code></pre>\n\n<p>Tags, once I removed them from my page the error no longer came up.</p>\n"
},
{
"answer_id": 429911,
"author": "user33090",
"author_id": 33090,
"author_profile": "https://Stackoverflow.com/users/33090",
"pm_score": 1,
"selected": false,
"text": "<p>I also found this bug in asp.net mvc beta. It can be very reproduced. After create asp.net mvc application using the default template, add a asp:button control to page home.aspx in design view, hit f5, the home page is displayed properly. click the button, this error will show up. After some debugging into the mvc source code, I found it is caused by the ViewUserControl in site.master page, just comment the <% Html.RenderPartial(\"LoginUserControl\"); %>, then the click event can be handled properly.</p>\n\n<p>I also found that setting like enableViewStateMac=\"false\" enableEventValidation=\"false\" viewStateEncryptionMode=\"Never\" is not useful. </p>\n\n<p>In the mvc source code the following section handle the ViewUserControl rendering</p>\n\n<p>public virtual void RenderView(ViewContext viewContext) {</p>\n\n<pre><code>// TODO: Remove this hack. Without it, the browser appears to always load cached output\nviewContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);\n**ViewUserControlContainerPage containerPage = new ViewUserControlContainerPage(this);**\n// Tracing requires Page IDs to be unique.\nID = Guid.NewGuid().ToString();\ncontainerPage.RenderView(viewContext);\n</code></pre>\n\n<p>}</p>\n\n<p>private sealed class ViewUserControlContainerPage : ViewPage {</p>\n\n<pre><code>public ViewUserControlContainerPage(ViewUserControl userControl) {\n Controls.Add(userControl);\n}\n</code></pre>\n\n<p>}</p>\n\n<p>the ViewUserControl always render in a newly created container page, this page will not pick your setting. In fact if step to this section, manually change the container.enableViewStateMac to false, does help to kill the error. So the only way to solve it is to ask Microsoft to change the mvc code.</p>\n"
},
{
"answer_id": 557597,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 1,
"selected": false,
"text": "<p>This issue on Microsoft Connect:</p>\n\n<p><a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=393619\" rel=\"nofollow noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=393619</a></p>\n"
},
{
"answer_id": 557611,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 3,
"selected": false,
"text": "<p>I worked around this by having my view user control inherit from this class instead of <code>ViewUserControl<T></code> (it's kind of a patch for RenderView). It did the trick for me, hopefully it works for you too.</p>\n\n<pre><code>public class ViewUserControlWithoutViewState<T> : ViewUserControl<T> where T : class {\n protected override void LoadViewState(object savedState) {}\n\n protected override object SaveControlState() {\n return null;\n }\n\n protected override void LoadControlState(object savedState) {}\n\n protected override object SaveViewState() {\n return null;\n }\n\n /// <summary>\n /// extracted from System.Web.Mvc.ViewUserControl\n /// </summary>\n /// <param name=\"viewContext\"></param>\n public override void RenderView(ViewContext viewContext) {\n viewContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);\n var containerPage = new ViewUserControlContainerPage(this);\n ID = Guid.NewGuid().ToString();\n RenderViewAndRestoreContentType(containerPage, viewContext);\n }\n\n /// <summary>\n /// extracted from System.Web.Mvc.ViewUserControl\n /// </summary>\n /// <param name=\"containerPage\"></param>\n /// <param name=\"viewContext\"></param>\n public static void RenderViewAndRestoreContentType(ViewPage containerPage, ViewContext viewContext) {\n string contentType = viewContext.HttpContext.Response.ContentType;\n containerPage.RenderView(viewContext);\n viewContext.HttpContext.Response.ContentType = contentType;\n }\n\n /// <summary>\n /// Extracted from System.Web.Mvc.ViewUserControl+ViewUserControlContainerPage\n /// </summary>\n private sealed class ViewUserControlContainerPage : ViewPage {\n // Methods\n public ViewUserControlContainerPage(ViewUserControl userControl) {\n Controls.Add(userControl);\n EnableViewState = false;\n }\n\n protected override object LoadPageStateFromPersistenceMedium() {\n return null;\n }\n\n protected override void SavePageStateToPersistenceMedium(object state) {}\n }\n}\n</code></pre>\n\n<p>I <a href=\"http://bugsquash.blogspot.com/2009/02/aspnet-mvc-postback-support.html\" rel=\"nofollow noreferrer\">blogged about this</a> some time ago.</p>\n"
},
{
"answer_id": 2721617,
"author": "isuruceanu",
"author_id": 106951,
"author_profile": "https://Stackoverflow.com/users/106951",
"pm_score": 0,
"selected": false,
"text": "<p>Just try to clear cookies on your local machine. Had same issue and this helped.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm using the ASP.NET 3.5 SP1 System.Web.Routing with classic WebForms, as described in <http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/>
**All works fine**, I have custom SEO urls and even the postback works. **But there is a case where the postback always fails** and I get a:
*Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.*
Here is the scenario to reproduce the error:
1. Create a standard webform mypage.aspx with a button
2. Create a Route that maps "a/b/{id}" to "~/mypage.aspx"
3. When you execute the site, you can navigate <http://localhost:XXXX/a/b/something> the page works. But when you press the button you get the error. The error doen't happen when the Route is just "a/{id}".
It seems to be related to the number of sub-paths in the url. If there are at least 2 sub-paths the viewstate validation fails.
You get the error even with EnableViewStateMac="false".
Any ideas? Is it a bug?
Thanks
|
I worked around this by having my view user control inherit from this class instead of `ViewUserControl<T>` (it's kind of a patch for RenderView). It did the trick for me, hopefully it works for you too.
```
public class ViewUserControlWithoutViewState<T> : ViewUserControl<T> where T : class {
protected override void LoadViewState(object savedState) {}
protected override object SaveControlState() {
return null;
}
protected override void LoadControlState(object savedState) {}
protected override object SaveViewState() {
return null;
}
/// <summary>
/// extracted from System.Web.Mvc.ViewUserControl
/// </summary>
/// <param name="viewContext"></param>
public override void RenderView(ViewContext viewContext) {
viewContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
var containerPage = new ViewUserControlContainerPage(this);
ID = Guid.NewGuid().ToString();
RenderViewAndRestoreContentType(containerPage, viewContext);
}
/// <summary>
/// extracted from System.Web.Mvc.ViewUserControl
/// </summary>
/// <param name="containerPage"></param>
/// <param name="viewContext"></param>
public static void RenderViewAndRestoreContentType(ViewPage containerPage, ViewContext viewContext) {
string contentType = viewContext.HttpContext.Response.ContentType;
containerPage.RenderView(viewContext);
viewContext.HttpContext.Response.ContentType = contentType;
}
/// <summary>
/// Extracted from System.Web.Mvc.ViewUserControl+ViewUserControlContainerPage
/// </summary>
private sealed class ViewUserControlContainerPage : ViewPage {
// Methods
public ViewUserControlContainerPage(ViewUserControl userControl) {
Controls.Add(userControl);
EnableViewState = false;
}
protected override object LoadPageStateFromPersistenceMedium() {
return null;
}
protected override void SavePageStateToPersistenceMedium(object state) {}
}
}
```
I [blogged about this](http://bugsquash.blogspot.com/2009/02/aspnet-mvc-postback-support.html) some time ago.
|
230,037 |
<p>I am trying to figure out the best way to use Ant to precompile JSPs that will be deployed to an Oracle application server. Even though I am deploying to an Oracle app server I would like to avoid using Oracle's version of Ant.</p>
|
[
{
"answer_id": 230112,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure what you mean by Oracle's version of Ant but as I understand it you will need the oracle's ant task to do this job. <a href=\"http://download-west.oracle.com/docs/cd/B32110_01/web.1013/b28961/ojspc.htm\" rel=\"nofollow noreferrer\">This</a> page explains how to do it. You will be using the apache ant that you download from the apache website, but you need to use Oracle ant task library from Oracle to pre compile JSPs for Oracle.</p>\n"
},
{
"answer_id": 235744,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 3,
"selected": false,
"text": "<p>Oracle's JSP compiler is available in your oc4j install at ORACLE_HOME/j2ee/home/jsp/bin/ojspc</p>\n\n<p>Assuming your classpath is correct at the compand line you would run:</p>\n\n<p>ojspc your.war</p>\n\n<p>The war will get updated and place a jar in the WEB-INF/lib containing the pre-compiled JSPs. Note that if your pre-compiling JSPs you should also set the MAIN_MODE to 'JUSTRUN' to get the additional performance benefit of pre-compiling your JSPs. The JUSTRUN setting does what it implies, the OC4J container will no longer check for updated .jsp files. </p>\n\n<pre><code><servlet>\n <servlet-name>jsp</servlet-name>\n <servlet-class>oracle.jsp.runtimev2.JspServlet</servlet-class>\n <init-param>\n <param-name>main_mode</param-name>\n <param-value>justrun</param-value>\n </init-param>\n</servlet>\n</code></pre>\n\n<p>Once your comfortable with calling ojspc from the command line You can then begin to use the ANT tasks provided by Oracle. </p>\n\n<p><strong>Within ANT</strong></p>\n\n<pre><code><oracle:compileJsp file=\"dist/war/before-${app}war\"\n verbose=\"false\"\n output=\"dist/war/${app}.war\" />\n</code></pre>\n\n<p><strong>Your project tag should reference the oracle tasks:</strong></p>\n\n<pre><code><project name=\"your-name\" default=\"compile\" basedir=\".\" xmlns:oracle=\"antlib:oracle\">\n...\n</project>\n</code></pre>\n\n<p><strong>Update 02.22.2011</strong>\nYou can also just work with the ojspc jar directly and avoid trying to configure the oracle:compileJsp Task, the code below takes a war file and pre-compiles the JSPS in it.</p>\n\n<pre><code> <!-- Now Precompile the War File (see entry in <project> tag ) -->\n <java jar=\"${env.ORACLE_HOME}/j2ee/home/ojspc.jar\" classpathref=\"jspPreCompileClassPath\" fork=\"true\">\n <arg value=\"-addClasspath\"/>\n <arg pathref=\"classpath\"/>\n <arg line=\"'${dist}/war/a-war-file.war'\"/>\n </java>\n</code></pre>\n\n<p>the jspPreCompileClassPath defnition looks like this:</p>\n\n<pre><code> <path id=\"jspPreCompileClassPath\">\n <path location=\"${env.ORACLE_HOME}/j2ee/home/lib/pcl.jar\"/>\n <path location=\"${env.ORACLE_HOME}/j2ee/home/lib/ojsp.jar\"/>\n <path location=\"${env.ORACLE_HOME}/j2ee/home/lib/oc4j-internal.jar\"/>\n <path location=\"${env.ORACLE_HOME}/j2ee/home/lib/servlet.jar\"/>\n <path location=\"${env.ORACLE_HOME}/j2ee/home/lib/commons-el.jar\"/>\n <path location=\"${env.ORACLE_HOME}/j2ee/home/lib/bcel.jar\"/>\n <path location=\"${env.ORACLE_HOME}/lib/xmlparserv2.jar\"/>\n <path location=\"${env.ORACLE_HOME}/j2ee/home/lib/oc4j-schemas.jar\"/>\n <path location=\"${env.ORACLE_HOME}/j2ee/home/jsp/lib/taglib/ojsputil.jar\"/>\n </path>\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25502/"
] |
I am trying to figure out the best way to use Ant to precompile JSPs that will be deployed to an Oracle application server. Even though I am deploying to an Oracle app server I would like to avoid using Oracle's version of Ant.
|
Oracle's JSP compiler is available in your oc4j install at ORACLE\_HOME/j2ee/home/jsp/bin/ojspc
Assuming your classpath is correct at the compand line you would run:
ojspc your.war
The war will get updated and place a jar in the WEB-INF/lib containing the pre-compiled JSPs. Note that if your pre-compiling JSPs you should also set the MAIN\_MODE to 'JUSTRUN' to get the additional performance benefit of pre-compiling your JSPs. The JUSTRUN setting does what it implies, the OC4J container will no longer check for updated .jsp files.
```
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>oracle.jsp.runtimev2.JspServlet</servlet-class>
<init-param>
<param-name>main_mode</param-name>
<param-value>justrun</param-value>
</init-param>
</servlet>
```
Once your comfortable with calling ojspc from the command line You can then begin to use the ANT tasks provided by Oracle.
**Within ANT**
```
<oracle:compileJsp file="dist/war/before-${app}war"
verbose="false"
output="dist/war/${app}.war" />
```
**Your project tag should reference the oracle tasks:**
```
<project name="your-name" default="compile" basedir="." xmlns:oracle="antlib:oracle">
...
</project>
```
**Update 02.22.2011**
You can also just work with the ojspc jar directly and avoid trying to configure the oracle:compileJsp Task, the code below takes a war file and pre-compiles the JSPS in it.
```
<!-- Now Precompile the War File (see entry in <project> tag ) -->
<java jar="${env.ORACLE_HOME}/j2ee/home/ojspc.jar" classpathref="jspPreCompileClassPath" fork="true">
<arg value="-addClasspath"/>
<arg pathref="classpath"/>
<arg line="'${dist}/war/a-war-file.war'"/>
</java>
```
the jspPreCompileClassPath defnition looks like this:
```
<path id="jspPreCompileClassPath">
<path location="${env.ORACLE_HOME}/j2ee/home/lib/pcl.jar"/>
<path location="${env.ORACLE_HOME}/j2ee/home/lib/ojsp.jar"/>
<path location="${env.ORACLE_HOME}/j2ee/home/lib/oc4j-internal.jar"/>
<path location="${env.ORACLE_HOME}/j2ee/home/lib/servlet.jar"/>
<path location="${env.ORACLE_HOME}/j2ee/home/lib/commons-el.jar"/>
<path location="${env.ORACLE_HOME}/j2ee/home/lib/bcel.jar"/>
<path location="${env.ORACLE_HOME}/lib/xmlparserv2.jar"/>
<path location="${env.ORACLE_HOME}/j2ee/home/lib/oc4j-schemas.jar"/>
<path location="${env.ORACLE_HOME}/j2ee/home/jsp/lib/taglib/ojsputil.jar"/>
</path>
```
|
230,062 |
<p>Is there a better way than simply trying to open the file?</p>
<pre><code>int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
</code></pre>
|
[
{
"answer_id": 230067,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 5,
"selected": false,
"text": "<p>Yes. Use <code>stat()</code>. See the man page for<a href=\"http://linux.die.net/man/2/stat\" rel=\"noreferrer\"><code>stat(2)</code></a>.</p>\n\n<p><code>stat()</code> will fail if the file doesn't exist, otherwise most likely succeed. If it does exist, but you have no read access to the directory where it exists, it will also fail, but in that case any method will fail (how can you inspect the content of a directory you may not see according to access rights? Simply, you can't).</p>\n\n<p>Oh, as someone else mentioned, you can also use <code>access()</code>. However I prefer <code>stat()</code>, as if the file exists it will immediately get me lots of useful information (when was it last updated, how big is it, owner and/or group that owns the file, access permissions, and so on).</p>\n"
},
{
"answer_id": 230068,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 11,
"selected": true,
"text": "<p>Look up the <code>access()</code> function, found in <code>unistd.h</code>. You can replace your function with</p>\n<pre><code>if (access(fname, F_OK) == 0) {\n // file exists\n} else {\n // file doesn't exist\n}\n</code></pre>\n<p>Under Windows (VC) <code>unistd.h</code> does not exist. To make it work it is necessary to define:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#ifdef WIN32\n#include <io.h>\n#define F_OK 0\n#define access _access\n#endif\n</code></pre>\n<p>You can also use <code>R_OK</code>, <code>W_OK</code>, and <code>X_OK</code> in place of <code>F_OK</code> to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read <em>and</em> write permission using <code>R_OK|W_OK</code>)</p>\n<p><em>Update</em>: Note that on Windows, you can't use <code>W_OK</code> to reliably test for write permission, since the access function does not take DACLs into account. <code>access( fname, W_OK )</code> may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.</p>\n"
},
{
"answer_id": 230070,
"author": "codebunny",
"author_id": 13667,
"author_profile": "https://Stackoverflow.com/users/13667",
"pm_score": 7,
"selected": false,
"text": "<p>Use <code>stat</code> like this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <sys/stat.h> // stat\n#include <stdbool.h> // bool type\n\nbool file_exists (char *filename) {\n struct stat buffer; \n return (stat (filename, &buffer) == 0);\n}\n</code></pre>\n\n<p>and call it like this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h> // printf\n\nint main(int ac, char **av) {\n if (ac != 2)\n return 1;\n\n if (file_exists(av[1]))\n printf(\"%s exists\\n\", av[1]);\n else\n printf(\"%s does not exist\\n\", av[1]);\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 230090,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 3,
"selected": false,
"text": "<p>From the Visual C++ help, I'd tend to go with</p>\n\n<pre><code>/* ACCESS.C: This example uses _access to check the\n * file named \"ACCESS.C\" to see if it exists and if\n * writing is allowed.\n */\n\n#include <io.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid main( void )\n{\n /* Check for existence */\n if( (_access( \"ACCESS.C\", 0 )) != -1 )\n {\n printf( \"File ACCESS.C exists\\n\" );\n /* Check for write permission */\n if( (_access( \"ACCESS.C\", 2 )) != -1 )\n printf( \"File ACCESS.C has write permission\\n\" );\n }\n}\n</code></pre>\n\n<p>Also worth noting mode values of <code>_access(const char *path,</code><strong><code>int mode</code></strong><code>)</code>:</p>\n\n<ul>\n<li><p>00: Existence only</p></li>\n<li><p>02: Write permission </p></li>\n<li><p>04: Read permission</p></li>\n<li><p>06: Read and write permission </p></li>\n</ul>\n\n<p>As your <code>fopen</code> could fail in situations where the file existed but could not be opened as requested.</p>\n\n<p>Edit: Just read Mecki's post. <code>stat()</code> does look like a neater way to go. Ho hum.</p>\n"
},
{
"answer_id": 230581,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 7,
"selected": false,
"text": "<p>Usually when you want to check if a file exists, it's because you want to <em>create</em> that file if it doesn't. <a href=\"https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c/230068#230068\">Graeme Perrow's answer</a> is good if you <strong>don't</strong> want to create that file, but it's vulnerable to a race condition if you do: another process could create the file in between you checking if it exists, and you actually opening it to write to it. (Don't laugh... this could have <strong>bad</strong> security implications if the file created was a symlink!)</p>\n\n<p>If you want to check for existence <em>and</em> create the file if it doesn't exist, <strong>atomically</strong> so that there are no race conditions, then use this:</p>\n\n<pre><code>#include <fcntl.h>\n#include <errno.h>\n\nfd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);\nif (fd < 0) {\n /* failure */\n if (errno == EEXIST) {\n /* the file already existed */\n ...\n }\n} else {\n /* now you can use the file */\n}\n</code></pre>\n"
},
{
"answer_id": 29510380,
"author": "mesutpiskin",
"author_id": 2647294,
"author_profile": "https://Stackoverflow.com/users/2647294",
"pm_score": 4,
"selected": false,
"text": "<pre><code>FILE *file;\n if((file = fopen(\"sample.txt\",\"r\"))!=NULL)\n {\n // file exists\n fclose(file);\n }\n else\n {\n //File not found, no memory leak since 'file' == NULL\n //fclose(file) would cause an error\n }\n</code></pre>\n"
},
{
"answer_id": 34184922,
"author": "Michi",
"author_id": 4745612,
"author_profile": "https://Stackoverflow.com/users/4745612",
"pm_score": 3,
"selected": false,
"text": "<p>I think that <a href=\"http://www.gnu.org/software/libc/manual/html_node/Testing-File-Access.html\" rel=\"noreferrer\">access()</a> function, which is found in <code>unistd.h</code> is a good choice for <code>Linux</code> (you can use <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html\" rel=\"noreferrer\">stat</a> too).</p>\n\n<p>You can Use it like this:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include<unistd.h>\n\nvoid fileCheck(const char *fileName);\n\nint main (void) {\n char *fileName = \"/etc/sudoers\";\n\n fileCheck(fileName);\n return 0;\n}\n\nvoid fileCheck(const char *fileName){\n\n if(!access(fileName, F_OK )){\n printf(\"The File %s\\t was Found\\n\",fileName);\n }else{\n printf(\"The File %s\\t not Found\\n\",fileName);\n }\n\n if(!access(fileName, R_OK )){\n printf(\"The File %s\\t can be read\\n\",fileName);\n }else{\n printf(\"The File %s\\t cannot be read\\n\",fileName);\n }\n\n if(!access( fileName, W_OK )){\n printf(\"The File %s\\t it can be Edited\\n\",fileName);\n }else{\n printf(\"The File %s\\t it cannot be Edited\\n\",fileName);\n }\n\n if(!access( fileName, X_OK )){\n printf(\"The File %s\\t is an Executable\\n\",fileName);\n }else{\n printf(\"The File %s\\t is not an Executable\\n\",fileName);\n }\n}\n</code></pre>\n\n<p>And you get the following Output:</p>\n\n<pre><code>The File /etc/sudoers was Found\nThe File /etc/sudoers cannot be read\nThe File /etc/sudoers it cannot be Edited\nThe File /etc/sudoers is not an Executable\n</code></pre>\n"
},
{
"answer_id": 36492773,
"author": "bharath reddy",
"author_id": 6175665,
"author_profile": "https://Stackoverflow.com/users/6175665",
"pm_score": 3,
"selected": false,
"text": "<p>You can use realpath() function.</p>\n\n<pre><code>resolved_file = realpath(file_path, NULL);\nif (!resolved_keyfile) {\n /*File dosn't exists*/\n perror(keyfile);\n return -1;\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1248/"
] |
Is there a better way than simply trying to open the file?
```
int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
```
|
Look up the `access()` function, found in `unistd.h`. You can replace your function with
```
if (access(fname, F_OK) == 0) {
// file exists
} else {
// file doesn't exist
}
```
Under Windows (VC) `unistd.h` does not exist. To make it work it is necessary to define:
```c
#ifdef WIN32
#include <io.h>
#define F_OK 0
#define access _access
#endif
```
You can also use `R_OK`, `W_OK`, and `X_OK` in place of `F_OK` to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read *and* write permission using `R_OK|W_OK`)
*Update*: Note that on Windows, you can't use `W_OK` to reliably test for write permission, since the access function does not take DACLs into account. `access( fname, W_OK )` may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.
|
230,065 |
<p>Are there any good (and preferably free) code coverage tools out there for Perl?</p>
|
[
{
"answer_id": 230083,
"author": "Sherm Pendley",
"author_id": 27631,
"author_profile": "https://Stackoverflow.com/users/27631",
"pm_score": 5,
"selected": false,
"text": "<p>As usual, CPAN is your friend: Have a look at <a href=\"https://metacpan.org/pod/Devel::Cover\" rel=\"nofollow noreferrer\">Devel::Cover</a></p>\n"
},
{
"answer_id": 230149,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, <a href=\"https://metacpan.org/pod/Devel::Cover\" rel=\"nofollow noreferrer\">Devel::Cover</a> is the way to go.</p>\n\n<p>If you develop a module, and use <a href=\"https://metacpan.org/pod/Module::Build\" rel=\"nofollow noreferrer\">Module::Build</a> to manage the installation, you even have a <code>testcover</code> target:</p>\n\n<pre><code> perl Build.PL\n ./Build testcover\n</code></pre>\n\n<p>That runs the whole test suite, and makes a combined coverage report in nice HTML, where you can browse through your modules and watch their coverage.</p>\n"
},
{
"answer_id": 232733,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 4,
"selected": false,
"text": "<p>As noted, Devel::Cover is your friend, but you'll want to google for it, too. It's documentation is a bit sparse and if you change your environment radically, you'll need to reinstall it because it builds Devel::Cover::Inc with a bunch of information pulled from your environment at the time you install it. This has caused plenty of problems for us at work as we have a shared CPAN environment and if one developer installs Devel::Cover and a different developer tries to run it, strange (and incorrect) results are common.</p>\n\n<p>If you use this module, also check out <a href=\"https://metacpan.org/pod/Devel::CoverX::Covered\" rel=\"nofollow noreferrer\">Devel::CoverX::Covered</a>. This module will capture much of the information which Devel::Cover throws away. It's very handy.</p>\n"
},
{
"answer_id": 236132,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 3,
"selected": false,
"text": "<p>Moritz discusses how modules built with Module::Build can use Devel::Cover easily.</p>\n\n<p>For modules using ExtUtils::MakeMaker, an extension module exists to invoke the same functionality. Adding the following code before the call to WriteMakefile():</p>\n\n<pre><code>eval \"use ExtUtils::MakeMaker::Coverage\";\nif( !$@ ) {\n print \"Adding testcover target\\n\";\n}\n</code></pre>\n\n<p>... will allow one to run the command 'make testcover' and have Devel::Cover perform its magic.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27687/"
] |
Are there any good (and preferably free) code coverage tools out there for Perl?
|
Yes, [Devel::Cover](https://metacpan.org/pod/Devel::Cover) is the way to go.
If you develop a module, and use [Module::Build](https://metacpan.org/pod/Module::Build) to manage the installation, you even have a `testcover` target:
```
perl Build.PL
./Build testcover
```
That runs the whole test suite, and makes a combined coverage report in nice HTML, where you can browse through your modules and watch their coverage.
|
230,081 |
<p>How do you find out the length/size of the data in an ntext column in SQL? - It's longer than 8000 bytes so I can't cast it to a varchar. Thanks.</p>
|
[
{
"answer_id": 230097,
"author": "korro",
"author_id": 22650,
"author_profile": "https://Stackoverflow.com/users/22650",
"pm_score": 7,
"selected": true,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/ms173486(SQL.90).aspx\" rel=\"noreferrer\">DataLength()</a></p>\n\n<pre><code>SELECT * FROM YourTable WHERE DataLength(NTextFieldName) > 0 \n</code></pre>\n"
},
{
"answer_id": 232828,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 4,
"selected": false,
"text": "<p>The clue's in the question: use <code>DATALENGTH()</code>. Note it has a different behaviour to <code>LEN()</code>:</p>\n\n<pre><code>SELECT LEN(CAST('Hello ' AS NVARCHAR(MAX))), \n DATALENGTH(CAST('Hello ' AS NVARCHAR(MAX))), \n DATALENGTH(CAST('Hello ' AS NTEXT))\n</code></pre>\n\n<p>returns 5, 16, 16.</p>\n\n<p>In other words, <code>DATALENGTH()</code> doesn't remove trailing spaces and returns the number of bytes, whereas <code>LEN()</code> trims the trailing spaces and returns the number of characters.</p>\n"
},
{
"answer_id": 45701317,
"author": "Steve D",
"author_id": 8469204,
"author_profile": "https://Stackoverflow.com/users/8469204",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Select Max(DataLength([NTextFieldName])) from YourTable\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] |
How do you find out the length/size of the data in an ntext column in SQL? - It's longer than 8000 bytes so I can't cast it to a varchar. Thanks.
|
Use [DataLength()](http://msdn.microsoft.com/en-us/library/ms173486(SQL.90).aspx)
```
SELECT * FROM YourTable WHERE DataLength(NTextFieldName) > 0
```
|
230,085 |
<p>We use Grid Control 10.2.0.4, with a catalog repository database also at 10.2.0.4. It seems that after a week or two of being up, the response time of the web interface gets very poor (20+ seconds to navigate to a new page, when normally 2-3 seconds is seen). The only thing we've found to overcome it is a restart of the catalog database and the GC/OMS. No errors reported in the alert log, just unbearable slowness. Are there any Oracle DBA's using GC out there who have seen this (and hopefully found a solution)? </p>
|
[
{
"answer_id": 230097,
"author": "korro",
"author_id": 22650,
"author_profile": "https://Stackoverflow.com/users/22650",
"pm_score": 7,
"selected": true,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/ms173486(SQL.90).aspx\" rel=\"noreferrer\">DataLength()</a></p>\n\n<pre><code>SELECT * FROM YourTable WHERE DataLength(NTextFieldName) > 0 \n</code></pre>\n"
},
{
"answer_id": 232828,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 4,
"selected": false,
"text": "<p>The clue's in the question: use <code>DATALENGTH()</code>. Note it has a different behaviour to <code>LEN()</code>:</p>\n\n<pre><code>SELECT LEN(CAST('Hello ' AS NVARCHAR(MAX))), \n DATALENGTH(CAST('Hello ' AS NVARCHAR(MAX))), \n DATALENGTH(CAST('Hello ' AS NTEXT))\n</code></pre>\n\n<p>returns 5, 16, 16.</p>\n\n<p>In other words, <code>DATALENGTH()</code> doesn't remove trailing spaces and returns the number of bytes, whereas <code>LEN()</code> trims the trailing spaces and returns the number of characters.</p>\n"
},
{
"answer_id": 45701317,
"author": "Steve D",
"author_id": 8469204,
"author_profile": "https://Stackoverflow.com/users/8469204",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Select Max(DataLength([NTextFieldName])) from YourTable\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8670/"
] |
We use Grid Control 10.2.0.4, with a catalog repository database also at 10.2.0.4. It seems that after a week or two of being up, the response time of the web interface gets very poor (20+ seconds to navigate to a new page, when normally 2-3 seconds is seen). The only thing we've found to overcome it is a restart of the catalog database and the GC/OMS. No errors reported in the alert log, just unbearable slowness. Are there any Oracle DBA's using GC out there who have seen this (and hopefully found a solution)?
|
Use [DataLength()](http://msdn.microsoft.com/en-us/library/ms173486(SQL.90).aspx)
```
SELECT * FROM YourTable WHERE DataLength(NTextFieldName) > 0
```
|
230,105 |
<p>What's the best data type in SQL to represent Decimal in .NET?</p>
<p>We want to store decimal numbers with up to 9 decimal place precision and want to avoid rounding errors etc on the front end.</p>
<p>Reading about data types, it appears using Decimal in .NET is the best option because you will not get rounding errors, although it is a bit slower than a Double.</p>
<p>We want to carry this through down to the DB and want minimum conversion issues when moving data through the layers. Any suggestions?</p>
|
[
{
"answer_id": 230118,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 3,
"selected": false,
"text": "<p>I would use the decimal type in SQL Server</p>\n\n<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/cc716729.aspx\" rel=\"nofollow noreferrer\">SQL Server Data Type Mappings (ADO.NET)</a></p>\n"
},
{
"answer_id": 230124,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using SQL Server, <a href=\"http://msdn.microsoft.com/en-us/library/ms131092.aspx\" rel=\"nofollow noreferrer\">this table</a> might help with data type mappings.</p>\n"
},
{
"answer_id": 2405477,
"author": "Gareth Farrington",
"author_id": 2021,
"author_profile": "https://Stackoverflow.com/users/2021",
"pm_score": 5,
"selected": false,
"text": "<p>So we did some testing on SQL Server. It looks like the sql type <code>decimal</code> cannot completely store any .net decimal.</p>\n\n<p>SQL Server can store a number up to <a href=\"http://msdn.microsoft.com/en-us/library/ms187746.aspx\" rel=\"noreferrer\">38 decimal digits long</a>. That's the total of the number of digits to the left and the right of the decimal place. You set a 'Scale', which tells SQL server how many decimal digits to reserve for the number to the right of the decimal place. If you set a scale then that takes away from the number of digits to the left of the decimal point. (Precision - Scale = number of decimal digits to the left of the decimal place)</p>\n\n<p>.NET can represent up to 28 digits to the right of the decimal point and 29 to the left. That would require a Precision of 57 in SQL Server but the max available is 38.</p>\n\n<p>So if you want to get as much <em>precision</em> as possible and your number are small enough then you could do this:</p>\n\n<pre><code>decimal(38, 28)\n</code></pre>\n\n<p>That would leave you with 10 digits to the left and 28 digits to the right. So any number larger than 9999999999 couldn't be represented but you wouldn't loose precision when doing currency type transactions.</p>\n\n<p>On the other hand if your numbers are <em>very large</em> you could store them with this declaration:</p>\n\n<pre><code>decimal(38, 9)\n</code></pre>\n\n<p>This would let you store the largest number that .net Decimal can store, which is 29 digits long. It would leave you with just 8 decimal digits of precision.</p>\n\n<p>If none of this sounds appealing then you can just store them as <code>varchar</code>. That would be allow you to save any .net decimal but it wouldn't let you perform any calculations on them in SQL.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30840/"
] |
What's the best data type in SQL to represent Decimal in .NET?
We want to store decimal numbers with up to 9 decimal place precision and want to avoid rounding errors etc on the front end.
Reading about data types, it appears using Decimal in .NET is the best option because you will not get rounding errors, although it is a bit slower than a Double.
We want to carry this through down to the DB and want minimum conversion issues when moving data through the layers. Any suggestions?
|
So we did some testing on SQL Server. It looks like the sql type `decimal` cannot completely store any .net decimal.
SQL Server can store a number up to [38 decimal digits long](http://msdn.microsoft.com/en-us/library/ms187746.aspx). That's the total of the number of digits to the left and the right of the decimal place. You set a 'Scale', which tells SQL server how many decimal digits to reserve for the number to the right of the decimal place. If you set a scale then that takes away from the number of digits to the left of the decimal point. (Precision - Scale = number of decimal digits to the left of the decimal place)
.NET can represent up to 28 digits to the right of the decimal point and 29 to the left. That would require a Precision of 57 in SQL Server but the max available is 38.
So if you want to get as much *precision* as possible and your number are small enough then you could do this:
```
decimal(38, 28)
```
That would leave you with 10 digits to the left and 28 digits to the right. So any number larger than 9999999999 couldn't be represented but you wouldn't loose precision when doing currency type transactions.
On the other hand if your numbers are *very large* you could store them with this declaration:
```
decimal(38, 9)
```
This would let you store the largest number that .net Decimal can store, which is 29 digits long. It would leave you with just 8 decimal digits of precision.
If none of this sounds appealing then you can just store them as `varchar`. That would be allow you to save any .net decimal but it wouldn't let you perform any calculations on them in SQL.
|
230,111 |
<p>I am trying to manipulate a string using Jython, I have included below an example string:</p>
<p>This would be a title for a website :: SiteName<br />
This would be a title for a website :: SiteName :: SiteName</p>
<p>How to remove all instances of ":: Sitename" or ":: SiteName :: SiteName"?</p>
|
[
{
"answer_id": 230240,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 3,
"selected": true,
"text": "<p>No different from regular Python:</p>\n\n<pre><code>>>> str=\"This would be a title for a website :: SiteName\"\n>>> str.replace(\":: SiteName\",\"\")\n'This would be a title for a website '\n>>> str=\"This would be a title for a website :: SiteName :: SiteName\"\n>>> str.replace(\":: SiteName\",\"\")\n'This would be a title for a website '\n</code></pre>\n"
},
{
"answer_id": 259472,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>For such simple example it is unnecessary but in general you could use <code>re</code> module.</p>\n\n<pre><code>import re\n\nsitename = \"sitename\" #NOTE: case-insensitive\nfor s in (\"This would be a title for a website :: SiteName :: SiteName\",\n \"This would be a title for a website :: SiteName\"):\n print(re.sub(r\"(?i)\\s*::\\s*%s\\s*\" % sitename, \"\", s))\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
I am trying to manipulate a string using Jython, I have included below an example string:
This would be a title for a website :: SiteName
This would be a title for a website :: SiteName :: SiteName
How to remove all instances of ":: Sitename" or ":: SiteName :: SiteName"?
|
No different from regular Python:
```
>>> str="This would be a title for a website :: SiteName"
>>> str.replace(":: SiteName","")
'This would be a title for a website '
>>> str="This would be a title for a website :: SiteName :: SiteName"
>>> str.replace(":: SiteName","")
'This would be a title for a website '
```
|
230,126 |
<p>I have a Timestamp value that comes from my application. The user can be in any given local TimeZone.</p>
<p>Since this date is used for a WebService that assumes the time given is always in GMT, I have a need to convert the user's parameter from say (EST) to (GMT). Here's the kicker: The user is oblivious to his TZ. He enters the creation date that he wants to send to the WS, so what I need is:</p>
<p><strong>User enters:</strong> 5/1/2008 6:12 PM (EST) <br>
<strong>The parameter to the WS needs to be</strong>: 5/1/2008 6:12 PM (GMT)</p>
<p>I know TimeStamps are always supposed to be in GMT by default, but when sending the parameter, even though I created my Calendar from the TS (which is supposed to be in GMT), the hours are always off unless the user is in GMT. What am I missing?</p>
<pre><code>Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
...
private static java.util.Calendar convertTimestampToJavaCalendar(Timestamp ts_) {
java.util.Calendar cal = java.util.Calendar.getInstance(
GMT_TIMEZONE, EN_US_LOCALE);
cal.setTimeInMillis(ts_.getTime());
return cal;
}
</code></pre>
<p>With the previous Code, this is what I get as a result (Short Format for easy reading):</p>
<p>[May 1, 2008 11:12 PM]</p>
|
[
{
"answer_id": 230313,
"author": "Adam",
"author_id": 30084,
"author_profile": "https://Stackoverflow.com/users/30084",
"pm_score": 2,
"selected": false,
"text": "<p>Something that has worked for me in the past was to determine the offset (in milliseconds) between the user's timezone and GMT. Once you have the offset, you can simply add/subtract (depending on which way the conversion is going) to get the appropriate time in either timezone. I would usually accomplish this by setting the milliseconds field of a Calendar object, but I'm sure you could easily apply it to a timestamp object. Here's the code I use to get the offset</p>\n\n<pre><code>int offset = TimeZone.getTimeZone(timezoneId).getRawOffset();\n</code></pre>\n\n<p>timezoneId is the id of the user's timezone (such as EST).</p>\n"
},
{
"answer_id": 230320,
"author": "Skip Head",
"author_id": 23271,
"author_profile": "https://Stackoverflow.com/users/23271",
"pm_score": 3,
"selected": false,
"text": "<p>It looks like your TimeStamp is being set to the timezone of the originating system.</p>\n\n<p>This is deprecated, but it should work:</p>\n\n<pre><code>cal.setTimeInMillis(ts_.getTime() - ts_.getTimezoneOffset());\n</code></pre>\n\n<p>The non-deprecated way is to use</p>\n\n<pre><code>Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)\n</code></pre>\n\n<p>but that would need to be done on the client side, since that system knows what timezone it is in.</p>\n"
},
{
"answer_id": 230383,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 6,
"selected": false,
"text": "<pre><code>public static Calendar convertToGmt(Calendar cal) {\n\n Date date = cal.getTime();\n TimeZone tz = cal.getTimeZone();\n\n log.debug(\"input calendar has date [\" + date + \"]\");\n\n //Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT \n long msFromEpochGmt = date.getTime();\n\n //gives you the current offset in ms from GMT at the current date\n int offsetFromUTC = tz.getOffset(msFromEpochGmt);\n log.debug(\"offset is \" + offsetFromUTC);\n\n //create a new calendar in GMT timezone, set to this date and add the offset\n Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\n gmtCal.setTime(date);\n gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);\n\n log.debug(\"Created GMT cal with date [\" + gmtCal.getTime() + \"]\");\n\n return gmtCal;\n}\n</code></pre>\n\n<p>Here's the output if I pass the current time (\"12:09:05 EDT\" from <code>Calendar.getInstance()</code>) in:</p>\n\n<blockquote>\n <p>DEBUG - input calendar has date [Thu Oct 23 12:09:05 EDT 2008]<br>\n DEBUG - offset is -14400000<br>\n DEBUG - Created GMT cal with date [Thu Oct 23 08:09:05 EDT 2008]</p>\n</blockquote>\n\n<p>12:09:05 GMT is 8:09:05 EDT.</p>\n\n<p>The confusing part here is that <code>Calendar.getTime()</code> returns you a <code>Date</code> in your current timezone, and also that there is no method to modify the timezone of a calendar and have the underlying date rolled also. Depending on what type of parameter your web service takes, your may just want to have the WS deal in terms of milliseconds from epoch.</p>\n"
},
{
"answer_id": 230765,
"author": "Jorge Valois",
"author_id": 30825,
"author_profile": "https://Stackoverflow.com/users/30825",
"pm_score": 6,
"selected": true,
"text": "<p>Thank you all for responding. After a further investigation I got to the right answer. As mentioned by Skip Head, the TimeStamped I was getting from my application was being adjusted to the user's TimeZone. So if the User entered 6:12 PM (EST) I would get 2:12 PM (GMT). What I needed was a way to undo the conversion so that the time entered by the user is the time I sent to the WebServer request. Here's how I accomplished this:</p>\n\n<pre><code>// Get TimeZone of user\nTimeZone currentTimeZone = sc_.getTimeZone();\nCalendar currentDt = new GregorianCalendar(currentTimeZone, EN_US_LOCALE);\n// Get the Offset from GMT taking DST into account\nint gmtOffset = currentTimeZone.getOffset(\n currentDt.get(Calendar.ERA), \n currentDt.get(Calendar.YEAR), \n currentDt.get(Calendar.MONTH), \n currentDt.get(Calendar.DAY_OF_MONTH), \n currentDt.get(Calendar.DAY_OF_WEEK), \n currentDt.get(Calendar.MILLISECOND));\n// convert to hours\ngmtOffset = gmtOffset / (60*60*1000);\nSystem.out.println(\"Current User's TimeZone: \" + currentTimeZone.getID());\nSystem.out.println(\"Current Offset from GMT (in hrs):\" + gmtOffset);\n// Get TS from User Input\nTimestamp issuedDate = (Timestamp) getACPValue(inputs_, \"issuedDate\");\nSystem.out.println(\"TS from ACP: \" + issuedDate);\n// Set TS into Calendar\nCalendar issueDate = convertTimestampToJavaCalendar(issuedDate);\n// Adjust for GMT (note the offset negation)\nissueDate.add(Calendar.HOUR_OF_DAY, -gmtOffset);\nSystem.out.println(\"Calendar Date converted from TS using GMT and US_EN Locale: \"\n + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)\n .format(issueDate.getTime()));\n</code></pre>\n\n<p>The code's output is: (User entered 5/1/2008 6:12PM (EST)</p>\n\n<p>Current User's TimeZone: EST<br>\nCurrent Offset from GMT (in hrs):-4 (Normally -5, except is DST adjusted)<br>\nTS from ACP: 2008-05-01 14:12:00.0<br>\nCalendar Date converted from TS using GMT and US_EN Locale: 5/1/08 6:12 PM (GMT)</p>\n"
},
{
"answer_id": 503072,
"author": "Henrik Aasted Sørensen",
"author_id": 13075,
"author_profile": "https://Stackoverflow.com/users/13075",
"pm_score": 4,
"selected": false,
"text": "<p>You say that the date is used in connection with web services, so I assume that is serialized into a string at some point.</p>\n\n<p>If this is the case, you should take a look at the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/text/DateFormat.html#setTimeZone(java.util.TimeZone)\" rel=\"noreferrer\">setTimeZone method</a> of the DateFormat class. This dictates which time zone that will be used when printing the time stamp.</p>\n\n<p>A simple example: </p>\n\n<pre><code>SimpleDateFormat formatter = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\");\nformatter.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\nCalendar cal = Calendar.getInstance();\nString timestamp = formatter.format(cal.getTime());\n</code></pre>\n"
},
{
"answer_id": 720813,
"author": "Helpa",
"author_id": 86210,
"author_profile": "https://Stackoverflow.com/users/86210",
"pm_score": 3,
"selected": false,
"text": "<p>Method for converting from one timeZone to other(probably it works :) ).</p>\n\n<pre><code>/**\n * Adapt calendar to client time zone.\n * @param calendar - adapting calendar\n * @param timeZone - client time zone\n * @return adapt calendar to client time zone\n */\npublic static Calendar convertCalendar(final Calendar calendar, final TimeZone timeZone) {\n Calendar ret = new GregorianCalendar(timeZone);\n ret.setTimeInMillis(calendar.getTimeInMillis() +\n timeZone.getOffset(calendar.getTimeInMillis()) -\n TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));\n ret.getTime();\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 8628145,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 4,
"selected": false,
"text": "<p>You can solve it with <a href=\"http://joda-time.sourceforge.net/\" rel=\"noreferrer\">Joda Time</a>:</p>\n\n<pre><code>Date utcDate = new Date(timezoneFrom.convertLocalToUTC(date.getTime(), false));\nDate localDate = new Date(timezoneTo.convertUTCToLocal(utcDate.getTime()));\n</code></pre>\n\n<p>Java 8:</p>\n\n<pre><code>LocalDateTime localDateTime = LocalDateTime.parse(\"2007-12-03T10:15:30\");\nZonedDateTime fromDateTime = localDateTime.atZone(\n ZoneId.of(\"America/Toronto\"));\nZonedDateTime toDateTime = fromDateTime.withZoneSameInstant(\n ZoneId.of(\"Canada/Newfoundland\"));\n</code></pre>\n"
},
{
"answer_id": 9159416,
"author": "user412090",
"author_id": 412090,
"author_profile": "https://Stackoverflow.com/users/412090",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Date</strong> and <strong>Timestamp</strong> objects are timezone-oblivious: they represent a certain number of seconds since the epoch, without committing to a particular interpretation of that instant as hours and days. \nTimezones enter the picture only in <strong>GregorianCalendar</strong> (not directly needed for this task) and <strong>SimpleDateFormat</strong>, which need a timezone offset to convert between separate fields and Date (or <em>long</em>) values.</p>\n\n<p>The OP's problem is right at the beginning of his processing: the user inputs hours, which are ambiguous, and they are interpreted in the local, non-GMT timezone; at this point the value is <em>\"6:12 EST\"</em>, which can be easily printed as <em>\"11.12 GMT\"</em> or any other timezone but is never going to <em>change</em> to <em>\"6.12 GMT\"</em>.</p>\n\n<p>There is no way to make the <strong>SimpleDateFormat</strong> that parses <em>\"06:12\"</em> as <em>\"HH:MM\"</em> (defaulting to the local time zone) default to UTC instead; <strong>SimpleDateFormat</strong> is a bit too smart for its own good.</p>\n\n<p>However, you can convince any <strong>SimpleDateFormat</strong> instance to use the right time zone if you put it explicitly in the input: just append a fixed string to the received (and adequately validated) <em>\"06:12\"</em> to parse <em>\"06:12 GMT\"</em> as <em>\"HH:MM z\"</em>. </p>\n\n<p>There is no need of explicit setting of <strong>GregorianCalendar</strong> fields or of retrieving and using timezone and daylight saving time offsets.</p>\n\n<p>The real problem is segregating inputs that default to the local timezone, inputs that default to UTC, and inputs that really require an explicit timezone indication.</p>\n"
},
{
"answer_id": 48456783,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "<h1>java.time</h1>\n\n<p>The modern approach uses the <em>java.time</em> classes that supplanted the troublesome legacy date-time classes bundled with the earliest versions of Java.</p>\n\n<p>The <code>java.sql.Timestamp</code> class is one of those legacy classes. No longer needed. Instead use <code>Instant</code> or other java.time classes directly with your database using JDBC 4.2 and later. </p>\n\n<p>The <a href=\"http://docs.oracle.com/javase/9/docs/api/java/time/Instant.html\" rel=\"nofollow noreferrer\"><code>Instant</code></a> class represents a moment on the timeline in <a href=\"https://en.wikipedia.org/wiki/Coordinated_Universal_Time\" rel=\"nofollow noreferrer\">UTC</a> with a resolution of <a href=\"https://en.wikipedia.org/wiki/Nanosecond\" rel=\"nofollow noreferrer\">nanoseconds</a> (up to nine (9) digits of a decimal fraction). </p>\n\n<pre><code>Instant instant = myResultSet.getObject( … , Instant.class ) ; \n</code></pre>\n\n<p>If you must interoperate with an existing <code>Timestamp</code>, convert immediately into java.time via the new conversion methods added to the old classes.</p>\n\n<pre><code>Instant instant = myTimestamp.toInstant() ;\n</code></pre>\n\n<p>To adjust into another time zone, specify the time zone as a <code>ZoneId</code> object. Specify a <a href=\"https://en.wikipedia.org/wiki/List_of_tz_zones_by_name\" rel=\"nofollow noreferrer\">proper time zone name</a> in the format of <code>continent/region</code>, such as <a href=\"https://en.wikipedia.org/wiki/America/Montreal\" rel=\"nofollow noreferrer\"><code>America/Montreal</code></a>, <a href=\"https://en.wikipedia.org/wiki/Africa/Casablanca\" rel=\"nofollow noreferrer\"><code>Africa/Casablanca</code></a>, or <code>Pacific/Auckland</code>. Never use the 3-4 letter pseudo-zones such as <code>EST</code> or <code>IST</code> as they are <em>not</em> true time zones, not standardized, and not even unique(!). </p>\n\n<pre><code>ZoneId z = ZoneId.of( \"America/Montreal\" ) ;\n</code></pre>\n\n<p>Apply to the <code>Instant</code> to produce a <code>ZonedDateTime</code> object.</p>\n\n<pre><code>ZonedDateTime zdt = instant.atZone( z ) ;\n</code></pre>\n\n<p>To generate a string for display to the user, search Stack Overflow for <code>DateTimeFormatter</code> to find many discussions and examples.</p>\n\n<p>Your Question is really about going the other direction, from user data-entry to the date-time objects. Generally best to break your data-entry into two parts, a date and a time-of-day.</p>\n\n<pre><code>LocalDate ld = LocalDate.parse( dateInput , DateTimeFormatter.ofPattern( \"M/d/uuuu\" , Locale.US ) ) ;\nLocalTime lt = LocalTime.parse( timeInput , DateTimeFormatter.ofPattern( \"H:m a\" , Locale.US ) ) ;\n</code></pre>\n\n<p>Your Question is not clear. Do you want to interpret the date and the time entered by the user to be in UTC? Or in another time zone?</p>\n\n<p>If you meant UTC, create a <code>OffsetDateTime</code> with an offset using the constant for UTC, <code>ZoneOffset.UTC</code>. </p>\n\n<pre><code>OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;\n</code></pre>\n\n<p>If you meant another time zone, combine along with a time zone object, a <code>ZoneId</code>. But which time zone? You might detect a default time zone. Or, if critical, you must confirm with the user to be certain of their intention.</p>\n\n<pre><code>ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;\n</code></pre>\n\n<p>To get a simpler object that is always in UTC by definition, extract an <code>Instant</code>.</p>\n\n<pre><code>Instant instant = odt.toInstant() ;\n</code></pre>\n\n<p>…or…</p>\n\n<pre><code>Instant instant = zdt.toInstant() ; \n</code></pre>\n\n<p>Send to your database.</p>\n\n<pre><code>myPreparedStatement.setObject( … , instant ) ;\n</code></pre>\n\n<hr>\n\n<h1>About java.time</h1>\n\n<p>The <a href=\"http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"nofollow noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Date.html\" rel=\"nofollow noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html\" rel=\"nofollow noreferrer\"><code>Calendar</code></a>, & <a href=\"http://docs.oracle.com/javase/9/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"nofollow noreferrer\">Joda-Time</a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"nofollow noreferrer\">maintenance mode</a>, advises migration to the <a href=\"http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\">Oracle Tutorial</a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"nofollow noreferrer\">JSR 310</a>.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"nofollow noreferrer\"><strong>Java SE 8</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"nofollow noreferrer\"><strong>Java SE 9</strong></a>, and later\n\n<ul>\n<li>Built-in. </li>\n<li>Part of the standard Java API with a bundled implementation.</li>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"nofollow noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"nofollow noreferrer\"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Much of the java.time functionality is back-ported to Java 6 & 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"nofollow noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the java.time classes.</li>\n<li>For earlier Android, the <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\"><strong><em>ThreeTenABP</em></strong></a> project adapts <em>ThreeTen-Backport</em> (mentioned above). See <a href=\"http://stackoverflow.com/q/38922754/642706\"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"nofollow noreferrer\"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html\" rel=\"nofollow noreferrer\"><code>Interval</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"nofollow noreferrer\"><code>YearWeek</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html\" rel=\"nofollow noreferrer\"><code>YearQuarter</code></a>, and <a href=\"http://www.threeten.org/threeten-extra/apidocs/index.html\" rel=\"nofollow noreferrer\">more</a>.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30825/"
] |
I have a Timestamp value that comes from my application. The user can be in any given local TimeZone.
Since this date is used for a WebService that assumes the time given is always in GMT, I have a need to convert the user's parameter from say (EST) to (GMT). Here's the kicker: The user is oblivious to his TZ. He enters the creation date that he wants to send to the WS, so what I need is:
**User enters:** 5/1/2008 6:12 PM (EST)
**The parameter to the WS needs to be**: 5/1/2008 6:12 PM (GMT)
I know TimeStamps are always supposed to be in GMT by default, but when sending the parameter, even though I created my Calendar from the TS (which is supposed to be in GMT), the hours are always off unless the user is in GMT. What am I missing?
```
Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
...
private static java.util.Calendar convertTimestampToJavaCalendar(Timestamp ts_) {
java.util.Calendar cal = java.util.Calendar.getInstance(
GMT_TIMEZONE, EN_US_LOCALE);
cal.setTimeInMillis(ts_.getTime());
return cal;
}
```
With the previous Code, this is what I get as a result (Short Format for easy reading):
[May 1, 2008 11:12 PM]
|
Thank you all for responding. After a further investigation I got to the right answer. As mentioned by Skip Head, the TimeStamped I was getting from my application was being adjusted to the user's TimeZone. So if the User entered 6:12 PM (EST) I would get 2:12 PM (GMT). What I needed was a way to undo the conversion so that the time entered by the user is the time I sent to the WebServer request. Here's how I accomplished this:
```
// Get TimeZone of user
TimeZone currentTimeZone = sc_.getTimeZone();
Calendar currentDt = new GregorianCalendar(currentTimeZone, EN_US_LOCALE);
// Get the Offset from GMT taking DST into account
int gmtOffset = currentTimeZone.getOffset(
currentDt.get(Calendar.ERA),
currentDt.get(Calendar.YEAR),
currentDt.get(Calendar.MONTH),
currentDt.get(Calendar.DAY_OF_MONTH),
currentDt.get(Calendar.DAY_OF_WEEK),
currentDt.get(Calendar.MILLISECOND));
// convert to hours
gmtOffset = gmtOffset / (60*60*1000);
System.out.println("Current User's TimeZone: " + currentTimeZone.getID());
System.out.println("Current Offset from GMT (in hrs):" + gmtOffset);
// Get TS from User Input
Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
System.out.println("TS from ACP: " + issuedDate);
// Set TS into Calendar
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
// Adjust for GMT (note the offset negation)
issueDate.add(Calendar.HOUR_OF_DAY, -gmtOffset);
System.out.println("Calendar Date converted from TS using GMT and US_EN Locale: "
+ DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
.format(issueDate.getTime()));
```
The code's output is: (User entered 5/1/2008 6:12PM (EST)
Current User's TimeZone: EST
Current Offset from GMT (in hrs):-4 (Normally -5, except is DST adjusted)
TS from ACP: 2008-05-01 14:12:00.0
Calendar Date converted from TS using GMT and US\_EN Locale: 5/1/08 6:12 PM (GMT)
|
230,128 |
<p>What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?</p>
|
[
{
"answer_id": 230141,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 11,
"selected": true,
"text": "<p><strong>From .NET 4.5 on, there is the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.stream.copytoasync.aspx\" rel=\"noreferrer\"><code>Stream.CopyToAsync</code> method</a></strong></p>\n\n<pre><code>input.CopyToAsync(output);\n</code></pre>\n\n<p>This will return a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx\" rel=\"noreferrer\"><code>Task</code></a> that can be continued on when completed, like so:</p>\n\n<pre><code>await input.CopyToAsync(output)\n\n// Code from here on will be run in a continuation.\n</code></pre>\n\n<p>Note that depending on where the call to <code>CopyToAsync</code> is made, the code that follows may or may not continue on the same thread that called it.</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx\" rel=\"noreferrer\"><code>SynchronizationContext</code></a> that was captured when calling <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx\" rel=\"noreferrer\"><code>await</code></a> will determine what thread the continuation will be executed on.</p>\n\n<p>Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).</p>\n\n<p><strong>From .NET 4.0 on, there's is the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.stream.copyto.aspx\" rel=\"noreferrer\"><code>Stream.CopyTo</code> method</a></strong></p>\n\n<pre><code>input.CopyTo(output);\n</code></pre>\n\n<p><strong>For .NET 3.5 and before</strong></p>\n\n<p>There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:</p>\n\n<pre><code>public static void CopyStream(Stream input, Stream output)\n{\n byte[] buffer = new byte[32768];\n int read;\n while ((read = input.Read(buffer, 0, buffer.Length)) > 0)\n {\n output.Write (buffer, 0, read);\n }\n}\n</code></pre>\n\n<p>Note 1: This method will allow you to report on progress (x bytes read so far ...)<br>\nNote 2: Why use a fixed buffer size and not <code>input.Length</code>? Because that Length may not be available! From the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.canseek\" rel=\"noreferrer\">docs</a>:</p>\n\n<blockquote>\n <p>If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.</p>\n</blockquote>\n"
},
{
"answer_id": 230175,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, there is no really simple solution. You can try something like that:</p>\n\n<pre><code>Stream s1, s2;\nbyte[] buffer = new byte[4096];\nint bytesRead = 0;\nwhile (bytesRead = s1.Read(buffer, 0, buffer.Length) > 0) s2.Write(buffer, 0, bytesRead);\ns1.Close(); s2.Close();\n</code></pre>\n\n<p>But the problem with that that different implementation of the Stream class might behave differently if there is nothing to read. A stream reading a file from a local harddrive will probably block until the read operaition has read enough data from the disk to fill the buffer and only return less data if it reaches the end of file. On the other hand, a stream reading from the network might return less data even though there are more data left to be received.</p>\n\n<p>Always check the documentation of the specific stream class you are using before using a generic solution.</p>\n"
},
{
"answer_id": 230190,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 1,
"selected": false,
"text": "<p>The basic questions that differentiate implementations of \"CopyStream\" are:</p>\n\n<ul>\n<li>size of the reading buffer</li>\n<li>size of the writes</li>\n<li>Can we use more than one thread (writing while we are reading).</li>\n</ul>\n\n<p>The answers to these questions result in vastly different implementations of CopyStream and are dependent on what kind of streams you have and what you are trying to optimize. The \"best\" implementation would even need to know what specific hardware the streams were reading and writing to.</p>\n"
},
{
"answer_id": 230625,
"author": "Coderer",
"author_id": 26286,
"author_profile": "https://Stackoverflow.com/users/26286",
"pm_score": 0,
"selected": false,
"text": "<p>There may be a way to do this more efficiently, depending on what kind of stream you're working with. If you can convert one or both of your streams to a MemoryStream, you can use the GetBuffer method to work directly with a byte array representing your data. This lets you use methods like Array.CopyTo, which abstract away all the issues raised by fryguybob. You can just trust .NET to know the optimal way to copy the data.</p>\n"
},
{
"answer_id": 671270,
"author": "Kronass",
"author_id": 81106,
"author_profile": "https://Stackoverflow.com/users/81106",
"pm_score": 0,
"selected": false,
"text": "<p>if you want a procdure to copy a stream to other the one that nick posted is fine but it is missing the position reset, it should be</p>\n\n<pre><code>public static void CopyStream(Stream input, Stream output)\n{\n byte[] buffer = new byte[32768];\n long TempPos = input.Position;\n while (true) \n {\n int read = input.Read (buffer, 0, buffer.Length);\n if (read <= 0)\n return;\n output.Write (buffer, 0, read);\n }\n input.Position = TempPos;// or you make Position = 0 to set it at the start\n}\n</code></pre>\n\n<p>but if it is in runtime not using a procedure you shpuld use memory stream</p>\n\n<pre><code>Stream output = new MemoryStream();\nbyte[] buffer = new byte[32768]; // or you specify the size you want of your buffer\nlong TempPos = input.Position;\nwhile (true) \n{\n int read = input.Read (buffer, 0, buffer.Length);\n if (read <= 0)\n return;\n output.Write (buffer, 0, read);\n }\n input.Position = TempPos;// or you make Position = 0 to set it at the start\n</code></pre>\n"
},
{
"answer_id": 1253015,
"author": "hannasm",
"author_id": 68042,
"author_profile": "https://Stackoverflow.com/users/68042",
"pm_score": 2,
"selected": false,
"text": "<p>There is actually, a less heavy-handed way of doing a stream copy. Take note however, that this implies that you can store the entire file in memory. Don't try and use this if you are working with files that go into the hundreds of megabytes or more, without caution.</p>\n<pre><code>public static void CopySmallTextStream(Stream input, Stream output)\n{\n using (StreamReader reader = new StreamReader(input))\n using (StreamWriter writer = new StreamWriter(output))\n {\n writer.Write(reader.ReadToEnd());\n }\n}\n</code></pre>\n<p><em>NOTE: There may also be some issues concerning binary data and character encodings.</em></p>\n"
},
{
"answer_id": 1253049,
"author": "Eloff",
"author_id": 152580,
"author_profile": "https://Stackoverflow.com/users/152580",
"pm_score": 5,
"selected": false,
"text": "<p>I use the following extension methods. They have optimized overloads for when one stream is a MemoryStream.</p>\n\n<pre><code> public static void CopyTo(this Stream src, Stream dest)\n {\n int size = (src.CanSeek) ? Math.Min((int)(src.Length - src.Position), 0x2000) : 0x2000;\n byte[] buffer = new byte[size];\n int n;\n do\n {\n n = src.Read(buffer, 0, buffer.Length);\n dest.Write(buffer, 0, n);\n } while (n != 0); \n }\n\n public static void CopyTo(this MemoryStream src, Stream dest)\n {\n dest.Write(src.GetBuffer(), (int)src.Position, (int)(src.Length - src.Position));\n }\n\n public static void CopyTo(this Stream src, MemoryStream dest)\n {\n if (src.CanSeek)\n {\n int pos = (int)dest.Position;\n int length = (int)(src.Length - src.Position) + pos;\n dest.SetLength(length); \n\n while(pos < length) \n pos += src.Read(dest.GetBuffer(), pos, length - pos);\n }\n else\n src.CopyTo((Stream)dest);\n }\n</code></pre>\n"
},
{
"answer_id": 3089903,
"author": "Joshua",
"author_id": 368954,
"author_profile": "https://Stackoverflow.com/users/368954",
"pm_score": 6,
"selected": false,
"text": "<p><code>MemoryStream</code> has <code>.WriteTo(outstream);</code></p>\n<p>and .NET 4.0 has <code>.CopyTo</code> on normal stream object.</p>\n<p>.NET 4.0:</p>\n<pre><code>instream.CopyTo(outstream);\n</code></pre>\n"
},
{
"answer_id": 8042598,
"author": "mdonatas",
"author_id": 79981,
"author_profile": "https://Stackoverflow.com/users/79981",
"pm_score": 0,
"selected": false,
"text": "<p>Since none of the answers have covered an asynchronous way of copying from one stream to another, here is a pattern that I've successfully used in a port forwarding application to copy data from one network stream to another. It lacks exception handling to emphasize the pattern.</p>\n\n<pre><code>const int BUFFER_SIZE = 4096;\n\nstatic byte[] bufferForRead = new byte[BUFFER_SIZE];\nstatic byte[] bufferForWrite = new byte[BUFFER_SIZE];\n\nstatic Stream sourceStream = new MemoryStream();\nstatic Stream destinationStream = new MemoryStream();\n\nstatic void Main(string[] args)\n{\n // Initial read from source stream\n sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);\n}\n\nprivate static void BeginReadCallback(IAsyncResult asyncRes)\n{\n // Finish reading from source stream\n int bytesRead = sourceStream.EndRead(asyncRes);\n // Make a copy of the buffer as we'll start another read immediately\n Array.Copy(bufferForRead, 0, bufferForWrite, 0, bytesRead);\n // Write copied buffer to destination stream\n destinationStream.BeginWrite(bufferForWrite, 0, bytesRead, BeginWriteCallback, null);\n // Start the next read (looks like async recursion I guess)\n sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);\n}\n\nprivate static void BeginWriteCallback(IAsyncResult asyncRes)\n{\n // Finish writing to destination stream\n destinationStream.EndWrite(asyncRes);\n}\n</code></pre>\n"
},
{
"answer_id": 11684353,
"author": "Jayesh Sorathia",
"author_id": 1282729,
"author_profile": "https://Stackoverflow.com/users/1282729",
"pm_score": 2,
"selected": false,
"text": "<p>.NET Framework 4 introduce new \"CopyTo\" method of Stream Class of System.IO namespace. Using this method we can copy one stream to another stream of different stream class. </p>\n\n<p>Here is example for this.</p>\n\n<pre><code> FileStream objFileStream = File.Open(Server.MapPath(\"TextFile.txt\"), FileMode.Open);\n Response.Write(string.Format(\"FileStream Content length: {0}\", objFileStream.Length.ToString()));\n\n MemoryStream objMemoryStream = new MemoryStream();\n\n // Copy File Stream to Memory Stream using CopyTo method\n objFileStream.CopyTo(objMemoryStream);\n Response.Write(\"<br/><br/>\");\n Response.Write(string.Format(\"MemoryStream Content length: {0}\", objMemoryStream.Length.ToString()));\n Response.Write(\"<br/><br/>\");\n</code></pre>\n"
},
{
"answer_id": 17382532,
"author": "ntiago",
"author_id": 2534996,
"author_profile": "https://Stackoverflow.com/users/2534996",
"pm_score": 0,
"selected": false,
"text": "<p>For .NET 3.5 and before try :</p>\n\n<pre><code>MemoryStream1.WriteTo(MemoryStream2);\n</code></pre>\n"
},
{
"answer_id": 50100908,
"author": "Graham Laight",
"author_id": 1649135,
"author_profile": "https://Stackoverflow.com/users/1649135",
"pm_score": 0,
"selected": false,
"text": "<p>Easy and safe - make new stream from original source:</p>\n\n<pre><code> MemoryStream source = new MemoryStream(byteArray);\n MemoryStream copy = new MemoryStream(byteArray);\n</code></pre>\n"
},
{
"answer_id": 63276155,
"author": "HasH",
"author_id": 1817702,
"author_profile": "https://Stackoverflow.com/users/1817702",
"pm_score": -1,
"selected": false,
"text": "<p>The following code to solve the issue copy the Stream to MemoryStream using CopyTo</p>\n<pre><code>Stream stream = new MemoryStream();\n</code></pre>\n<p>//any function require input the stream. In mycase to save the PDF file as stream\ndocument.Save(stream);</p>\n<pre><code>MemoryStream newMs = (MemoryStream)stream;\n\nbyte[] getByte = newMs.ToArray();\n</code></pre>\n<p>//Note - please dispose the stream in the finally block instead of inside using block as it will throw an error 'Access denied as the stream is closed'</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341413/"
] |
What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?
|
**From .NET 4.5 on, there is the [`Stream.CopyToAsync` method](http://msdn.microsoft.com/en-us/library/system.io.stream.copytoasync.aspx)**
```
input.CopyToAsync(output);
```
This will return a [`Task`](http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx) that can be continued on when completed, like so:
```
await input.CopyToAsync(output)
// Code from here on will be run in a continuation.
```
Note that depending on where the call to `CopyToAsync` is made, the code that follows may or may not continue on the same thread that called it.
The [`SynchronizationContext`](http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx) that was captured when calling [`await`](http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx) will determine what thread the continuation will be executed on.
Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).
**From .NET 4.0 on, there's is the [`Stream.CopyTo` method](http://msdn.microsoft.com/en-us/library/system.io.stream.copyto.aspx)**
```
input.CopyTo(output);
```
**For .NET 3.5 and before**
There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:
```
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
```
Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not `input.Length`? Because that Length may not be available! From the [docs](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.canseek):
>
> If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.
>
>
>
|
230,129 |
<p>I've been experimenting with fulltext search lately and am curious about the meaning of the Score value. For example I have the following query:</p>
<pre><code>SELECT table. * ,
MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
) AS Score
FROM table
WHERE MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
)
</code></pre>
<p>In the results for Score I've seen results, for one query, between 0.4667041301727 to 11.166275978088. I get that it's MySQLs idea of relevance (the higher the more weight).</p>
<p>What I don't get is how MySQL comes up with that score. Why is the number not returned as a decimal or something besides ? </p>
<p>How come if I run a query "IN BOOLEAN MODE" does the score always return a 1 or a 0 ? Wouldn't all the results be a 1?</p>
<p>Just hoping for some enlightenment. Thanks.</p>
|
[
{
"answer_id": 230219,
"author": "Harrison Fisk",
"author_id": 16111,
"author_profile": "https://Stackoverflow.com/users/16111",
"pm_score": 4,
"selected": true,
"text": "<p>Generally relevance is based on how many matches each row has to the words given to the search. The exact value will depend on many things, but it really only matters for comparing to other relevance values in the same query.</p>\n\n<p>If you really want the math behind it, you can find it at the <a href=\"https://dev.mysql.com/doc/refman/5.7/en/fulltext-search.html\" rel=\"nofollow noreferrer\">internals manual</a>.</p>\n"
},
{
"answer_id": 233212,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 4,
"selected": false,
"text": "<p>Take the query \"word1 word2\" as an example.</p>\n\n<p>BOOLEAN mode indicates that your entire query matches the document (e.g. it contains both word1 AND word2). Boolean mode is a strict match.</p>\n\n<p>The formula normally used is based on the Vector Space Model of searching. Very simplified, it figures out two measures to determine how important a word is to a query. The term frequency (terms that occur often in a document are more important than other terms) and the inverse document frequency (a term that occurs in many documents is weighted lower than a term that occurs in few documents). This is known as <a href=\"http://en.wikipedia.org/wiki/Tf-idf\" rel=\"nofollow noreferrer\">tf-idf</a>, and is used as a basis for the vector space model. These scores form the basis for the <a href=\"http://en.wikipedia.org/wiki/Vector_space_model\" rel=\"nofollow noreferrer\">Vector Space Model</a>, which someone else can explain thoroughly. :)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538/"
] |
I've been experimenting with fulltext search lately and am curious about the meaning of the Score value. For example I have the following query:
```
SELECT table. * ,
MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
) AS Score
FROM table
WHERE MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
)
```
In the results for Score I've seen results, for one query, between 0.4667041301727 to 11.166275978088. I get that it's MySQLs idea of relevance (the higher the more weight).
What I don't get is how MySQL comes up with that score. Why is the number not returned as a decimal or something besides ?
How come if I run a query "IN BOOLEAN MODE" does the score always return a 1 or a 0 ? Wouldn't all the results be a 1?
Just hoping for some enlightenment. Thanks.
|
Generally relevance is based on how many matches each row has to the words given to the search. The exact value will depend on many things, but it really only matters for comparing to other relevance values in the same query.
If you really want the math behind it, you can find it at the [internals manual](https://dev.mysql.com/doc/refman/5.7/en/fulltext-search.html).
|
230,138 |
<p>I have a table that was imported as all UPPER CASE and I would like to turn it into Proper Case. What script have any of you used to complete this?</p>
|
[
{
"answer_id": 230177,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 8,
"selected": true,
"text": "<p>Here's a UDF that will do the trick...</p>\n\n<pre><code>create function ProperCase(@Text as varchar(8000))\nreturns varchar(8000)\nas\nbegin\n declare @Reset bit;\n declare @Ret varchar(8000);\n declare @i int;\n declare @c char(1);\n\n if @Text is null\n return null;\n\n select @Reset = 1, @i = 1, @Ret = '';\n\n while (@i <= len(@Text))\n select @c = substring(@Text, @i, 1),\n @Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,\n @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,\n @i = @i + 1\n return @Ret\nend\n</code></pre>\n\n<p>You will still have to use it to update your data though.</p>\n"
},
{
"answer_id": 230224,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 7,
"selected": false,
"text": "<p>This function:</p>\n\n<ul>\n<li>\"Proper Cases\" all \"UPPER CASE\" words that are delimited by white space</li>\n<li>leaves \"lower case words\" alone</li>\n<li>works properly even for non-English alphabets</li>\n<li>is portable in that it does not use fancy features of recent SQL server versions</li>\n<li>can be easily changed to use NCHAR and NVARCHAR for unicode support,as well as any parameter length you see fit</li>\n<li>white space definition can be configured</li>\n</ul>\n\n\n\n<pre><code>CREATE FUNCTION ToProperCase(@string VARCHAR(255)) RETURNS VARCHAR(255)\nAS\nBEGIN\n DECLARE @i INT -- index\n DECLARE @l INT -- input length\n DECLARE @c NCHAR(1) -- current char\n DECLARE @f INT -- first letter flag (1/0)\n DECLARE @o VARCHAR(255) -- output string\n DECLARE @w VARCHAR(10) -- characters considered as white space\n\n SET @w = '[' + CHAR(13) + CHAR(10) + CHAR(9) + CHAR(160) + ' ' + ']'\n SET @i = 1\n SET @l = LEN(@string)\n SET @f = 1\n SET @o = ''\n\n WHILE @i <= @l\n BEGIN\n SET @c = SUBSTRING(@string, @i, 1)\n IF @f = 1 \n BEGIN\n SET @o = @o + @c\n SET @f = 0\n END\n ELSE\n BEGIN\n SET @o = @o + LOWER(@c)\n END\n\n IF @c LIKE @w SET @f = 1\n\n SET @i = @i + 1\n END\n\n RETURN @o\nEND\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>dbo.ToProperCase('ALL UPPER CASE and SOME lower ÄÄ ÖÖ ÜÜ ÉÉ ØØ ĈĈ ÆÆ')\n-----------------------------------------------------------------\nAll Upper Case and Some lower Ää Öö Üü Éé Øø Cc Ææ\n</code></pre>\n"
},
{
"answer_id": 230290,
"author": "Cervo",
"author_id": 16219,
"author_profile": "https://Stackoverflow.com/users/16219",
"pm_score": 0,
"selected": false,
"text": "<p>I think you will find that the following is more efficient:</p>\n\n<pre><code>IF OBJECT_ID('dbo.ProperCase') IS NOT NULL\n DROP FUNCTION dbo.ProperCase\nGO\nCREATE FUNCTION dbo.PROPERCASE (\n @str VARCHAR(8000))\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n SET @str = ' ' + @str\n SET @str = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @str, ' a', ' A'), ' b', ' B'), ' c', ' C'), ' d', ' D'), ' e', ' E'), ' f', ' F'), ' g', ' G'), ' h', ' H'), ' i', ' I'), ' j', ' J'), ' k', ' K'), ' l', ' L'), ' m', ' M'), ' n', ' N'), ' o', ' O'), ' p', ' P'), ' q', ' Q'), ' r', ' R'), ' s', ' S'), ' t', ' T'), ' u', ' U'), ' v', ' V'), ' w', ' W'), ' x', ' X'), ' y', ' Y'), ' z', ' Z')\n RETURN RIGHT(@str, LEN(@str) - 1)\nEND\nGO\n</code></pre>\n\n<p>The replace statement could be cut and pasted directly into a SQL query. It is ultra ugly, however by replacing @str with the column you are interested in, you will not pay a price for an implicit cursor like you will with the udfs thus posted. I find that even using my UDF it is much more efficient.</p>\n\n<p>Oh and instead of generating the replace statement by hand use this:</p>\n\n<pre><code>-- Code Generator for expression\nDECLARE @x INT,\n @c CHAR(1),\n @sql VARCHAR(8000)\nSET @x = 0\nSET @sql = '@str' -- actual variable/column you want to replace\nWHILE @x < 26\nBEGIN\n SET @c = CHAR(ASCII('a') + @x)\n SET @sql = 'REPLACE(' + @sql + ', '' ' + @c+ ''', '' ' + UPPER(@c) + ''')'\n SET @x = @x + 1\nEND\nPRINT @sql\n</code></pre>\n\n<p>Anyway it depends on the number of rows. I wish you could just do s/\\b([a-z])/uc $1/, but oh well we work with the tools we have.</p>\n\n<p>NOTE you would have to use this as you would have to use it as....SELECT dbo.ProperCase(LOWER(column)) since the column is in uppercase. It actually works pretty fast on my table of 5,000 entries (not even one second) even with the lower.</p>\n\n<p>In response to the flurry of comments regarding internationalization I present the following implementation that handles every ascii character relying only on SQL Server's Implementation of upper and lower. Remember, the variables we are using here are VARCHAR which means that they can only hold ASCII values. In order to use further international alphabets, you have to use NVARCHAR. The logic would be similar but you would need to use UNICODE and NCHAR in place of ASCII AND CHAR and the replace statement would be much more huge....</p>\n\n<pre><code>-- Code Generator for expression\nDECLARE @x INT,\n @c CHAR(1),\n @sql VARCHAR(8000),\n @count INT\nSEt @x = 0\nSET @count = 0\nSET @sql = '@str' -- actual variable you want to replace\nWHILE @x < 256\nBEGIN\n SET @c = CHAR(@x)\n -- Only generate replacement expression for characters where upper and lowercase differ\n IF @x = ASCII(LOWER(@c)) AND @x != ASCII(UPPER(@c))\n BEGIN\n SET @sql = 'REPLACE(' + @sql + ', '' ' + @c+ ''', '' ' + UPPER(@c) + ''')'\n SET @count = @count + 1\n END\n SET @x = @x + 1\nEND\nPRINT @sql\nPRINT 'Total characters substituted: ' + CONVERT(VARCHAR(255), @count)\n</code></pre>\n\n<p>Basically the premise of the my method is trading pre-computing for efficiency. The full ASCII implementation is as follows:</p>\n\n<pre><code>IF OBJECT_ID('dbo.ProperCase') IS NOT NULL\n DROP FUNCTION dbo.ProperCase\nGO\nCREATE FUNCTION dbo.PROPERCASE (\n @str VARCHAR(8000))\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n SET @str = ' ' + @str\nSET @str = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@str, ' a', ' A'), ' b', ' B'), ' c', ' C'), ' d', ' D'), ' e', ' E'), ' f', ' F'), ' g', ' G'), ' h', ' H'), ' i', ' I'), ' j', ' J'), ' k', ' K'), ' l', ' L'), ' m', ' M'), ' n', ' N'), ' o', ' O'), ' p', ' P'), ' q', ' Q'), ' r', ' R'), ' s', ' S'), ' t', ' T'), ' u', ' U'), ' v', ' V'), ' w', ' W'), ' x', ' X'), ' y', ' Y'), ' z', ' Z'), ' š', ' Š'), ' œ', ' Œ'), ' ž', ' Ž'), ' à', ' À'), ' á', ' Á'), ' â', ' Â'), ' ã', ' Ã'), ' ä', ' Ä'), ' å', ' Å'), ' æ', ' Æ'), ' ç', ' Ç'), ' è', ' È'), ' é', ' É'), ' ê', ' Ê'), ' ë', ' Ë'), ' ì', ' Ì'), ' í', ' Í'), ' î', ' Î'), ' ï', ' Ï'), ' ð', ' Ð'), ' ñ', ' Ñ'), ' ò', ' Ò'), ' ó', ' Ó'), ' ô', ' Ô'), ' õ', ' Õ'), ' ö', ' Ö'), ' ø', ' Ø'), ' ù', ' Ù'), ' ú', ' Ú'), ' û', ' Û'), ' ü', ' Ü'), ' ý', ' Ý'), ' þ', ' Þ'), ' ÿ', ' Ÿ')\n RETURN RIGHT(@str, LEN(@str) - 1)\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 230693,
"author": "Toybuilder",
"author_id": 22329,
"author_profile": "https://Stackoverflow.com/users/22329",
"pm_score": 0,
"selected": false,
"text": "<p>Is it too late to go back and get the un-uppercased data? </p>\n\n<p>The von Neumann's, McCain's, DeGuzman's, and the Johnson-Smith's of your client base may not like the result of your processing...</p>\n\n<p>Also, I'm guessing that this is intended to be a one-time upgrade of the data? It might be easier to export, filter/modify, and re-import the corrected names into the db, and then you can use non-SQL approaches to name fixing...</p>\n"
},
{
"answer_id": 231705,
"author": "nathan_jr",
"author_id": 3769,
"author_profile": "https://Stackoverflow.com/users/3769",
"pm_score": 1,
"selected": false,
"text": "<p>The link I posted above is a great option that addresses the main issue: that we can never programmatically account for all cases (Smith-Jones, von Haussen, John Smith M.D.), at least not in an elegant manner. Tony introduces the concept of an exception / break character to deal with these cases.\nAnyways, building on Cervo's idea (upper all lower chars preceded by space), the replace statements could be wrapped up in a single table based replace instead. Really, any low/up character combination could be inserted into @alpha and the statement would not change: </p>\n\n<pre><code>declare @str nvarchar(8000)\ndeclare @alpha table (low nchar(1), up nchar(1))\n\n\nset @str = 'ALL UPPER CASE and SOME lower ÄÄ ÖÖ ÜÜ ÉÉ ØØ ĈĈ ÆÆ'\n\n-- stage the alpha (needs number table)\ninsert into @alpha\n -- A-Z / a-z\n select nchar(n+32),\n nchar(n)\n from dbo.Number\n where n between 65 and 90 or\n n between 192 and 223\n\n-- append space at start of str\nset @str = lower(' ' + @str)\n\n-- upper all lower case chars preceded by space\nselect @str = replace(@str, ' ' + low, ' ' + up) \nfrom @Alpha\n\nselect @str\n</code></pre>\n"
},
{
"answer_id": 231728,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": false,
"text": "<p>If you can enable the CLR in SQL Server (requires 2005 or later) then you could <a href=\"http://msdn.microsoft.com/en-us/library/w2kae45k.aspx\" rel=\"noreferrer\">create a CLR function</a> that uses the <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx\" rel=\"noreferrer\">TextInfo.ToTitleCase built-in function</a> which would allow you to create a culture-aware way of doing this in only a few lines of code.</p>\n"
},
{
"answer_id": 1007802,
"author": "Merritt",
"author_id": 60385,
"author_profile": "https://Stackoverflow.com/users/60385",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another variation I found on the SQLTeam.com Forums @\n<a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47718\" rel=\"nofollow noreferrer\">http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47718</a></p>\n\n<pre><code>create FUNCTION PROPERCASE\n(\n--The string to be converted to proper case\n@input varchar(8000)\n)\n--This function returns the proper case string of varchar type\nRETURNS varchar(8000)\nAS\nBEGIN\nIF @input IS NULL\nBEGIN\n--Just return NULL if input string is NULL\nRETURN NULL\nEND\n\n--Character variable declarations\nDECLARE @output varchar(8000)\n--Integer variable declarations\nDECLARE @ctr int, @len int, @found_at int\n--Constant declarations\nDECLARE @LOWER_CASE_a int, @LOWER_CASE_z int, @Delimiter char(3), @UPPER_CASE_A int, @UPPER_CASE_Z int\n\n--Variable/Constant initializations\nSET @ctr = 1\nSET @len = LEN(@input)\nSET @output = ''\nSET @LOWER_CASE_a = 97\nSET @LOWER_CASE_z = 122\nSET @Delimiter = ' ,-'\nSET @UPPER_CASE_A = 65\nSET @UPPER_CASE_Z = 90\n\nWHILE @ctr <= @len\nBEGIN\n--This loop will take care of reccuring white spaces\nWHILE CHARINDEX(SUBSTRING(@input,@ctr,1), @Delimiter) > 0\nBEGIN\nSET @output = @output + SUBSTRING(@input,@ctr,1)\nSET @ctr = @ctr + 1\nEND\n\nIF ASCII(SUBSTRING(@input,@ctr,1)) BETWEEN @LOWER_CASE_a AND @LOWER_CASE_z\nBEGIN\n--Converting the first character to upper case\nSET @output = @output + UPPER(SUBSTRING(@input,@ctr,1))\nEND\nELSE\nBEGIN\nSET @output = @output + SUBSTRING(@input,@ctr,1)\nEND\n\nSET @ctr = @ctr + 1\n\nWHILE CHARINDEX(SUBSTRING(@input,@ctr,1), @Delimiter) = 0 AND (@ctr <= @len)\nBEGIN\nIF ASCII(SUBSTRING(@input,@ctr,1)) BETWEEN @UPPER_CASE_A AND @UPPER_CASE_Z\nBEGIN\nSET @output = @output + LOWER(SUBSTRING(@input,@ctr,1))\nEND\nELSE\nBEGIN\nSET @output = @output + SUBSTRING(@input,@ctr,1)\nEND\nSET @ctr = @ctr + 1\nEND\n\nEND\nRETURN @output\nEND\n\n\n\nGO\nSET QUOTED_IDENTIFIER OFF\nGO\nSET ANSI_NULLS ON\nGO\n</code></pre>\n"
},
{
"answer_id": 1764042,
"author": "Dennis Allen",
"author_id": 214691,
"author_profile": "https://Stackoverflow.com/users/214691",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a version that uses a sequence or numbers table rather than a loop. You can modify the WHERE clause to suite your personal rules for when to convert a character to upper case. I have just included a simple set that will upper case any letter that is proceeded by a non-letter with the exception of apostrophes. This does how ever mean that 123apple would have a match on the \"a\" because \"3\" is not a letter. If you want just white-space (space, tab, carriage-return, line-feed), you can replace the pattern <code>'[^a-z]'</code> with <code>'[' + Char(32) + Char(9) + Char(13) + Char(10) + ']'</code>.</p>\n\n<hr>\n\n<pre><code>CREATE FUNCTION String.InitCap( @string nvarchar(4000) ) RETURNS nvarchar(4000) AS\nBEGIN\n\n-- 1. Convert all letters to lower case\n DECLARE @InitCap nvarchar(4000); SET @InitCap = Lower(@string);\n\n-- 2. Using a Sequence, replace the letters that should be upper case with their upper case version\n SELECT @InitCap = Stuff( @InitCap, n, 1, Upper( SubString( @InitCap, n, 1 ) ) )\n FROM (\n SELECT (1 + n1.n + n10.n + n100.n + n1000.n) AS n\n FROM (SELECT 0 AS n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS n1\n CROSS JOIN (SELECT 0 AS n UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40 UNION SELECT 50 UNION SELECT 60 UNION SELECT 70 UNION SELECT 80 UNION SELECT 90) AS n10\n CROSS JOIN (SELECT 0 AS n UNION SELECT 100 UNION SELECT 200 UNION SELECT 300 UNION SELECT 400 UNION SELECT 500 UNION SELECT 600 UNION SELECT 700 UNION SELECT 800 UNION SELECT 900) AS n100\n CROSS JOIN (SELECT 0 AS n UNION SELECT 1000 UNION SELECT 2000 UNION SELECT 3000) AS n1000\n ) AS Sequence\n WHERE \n n BETWEEN 1 AND Len( @InitCap )\n AND SubString( @InitCap, n, 1 ) LIKE '[a-z]' /* this character is a letter */\n AND (\n n = 1 /* this character is the first `character` */\n OR SubString( @InitCap, n-1, 1 ) LIKE '[^a-z]' /* the previous character is NOT a letter */\n )\n AND (\n n < 3 /* only test the 3rd or greater characters for this exception */\n OR SubString( @InitCap, n-2, 3 ) NOT LIKE '[a-z]''[a-z]' /* exception: The pattern <letter>'<letter> should not capatolize the letter following the apostrophy */\n )\n\n-- 3. Return the modified version of the input\n RETURN @InitCap\n\nEND\n</code></pre>\n"
},
{
"answer_id": 6602923,
"author": "Lee",
"author_id": 832403,
"author_profile": "https://Stackoverflow.com/users/832403",
"pm_score": 1,
"selected": false,
"text": "<p>It would make sense to maintain a lookup of exceptions to take care of The von Neumann's, McCain's, DeGuzman's, and the Johnson-Smith's.</p>\n"
},
{
"answer_id": 20660732,
"author": "Richard Sayakanit",
"author_id": 302589,
"author_profile": "https://Stackoverflow.com/users/302589",
"pm_score": 6,
"selected": false,
"text": "<pre><code>UPDATE titles\n SET title =\n UPPER(LEFT(title, 1)) +\n LOWER(RIGHT(title, LEN(title) - 1))\n</code></pre>\n\n<p><a href=\"http://sqlmag.com/t-sql/how-title-case-column-value\" rel=\"noreferrer\">http://sqlmag.com/t-sql/how-title-case-column-value</a></p>\n"
},
{
"answer_id": 28712621,
"author": "Harmeet Singh Bhamra",
"author_id": 2758965,
"author_profile": "https://Stackoverflow.com/users/2758965",
"pm_score": 4,
"selected": false,
"text": "<p>I know this is late post in this thread but, worth looking. This function works for me ever time. So thought of sharing it.</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnConvert_TitleCase] (@InputString VARCHAR(4000) )\nRETURNS VARCHAR(4000)\nAS\nBEGIN\nDECLARE @Index INT\nDECLARE @Char CHAR(1)\nDECLARE @OutputString VARCHAR(255)\n\nSET @OutputString = LOWER(@InputString)\nSET @Index = 2\nSET @OutputString = STUFF(@OutputString, 1, 1,UPPER(SUBSTRING(@InputString,1,1)))\n\nWHILE @Index <= LEN(@InputString)\nBEGIN\n SET @Char = SUBSTRING(@InputString, @Index, 1)\n IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&','''','(')\n IF @Index + 1 <= LEN(@InputString)\nBEGIN\n IF @Char != ''''\n OR\n UPPER(SUBSTRING(@InputString, @Index + 1, 1)) != 'S'\n SET @OutputString =\n STUFF(@OutputString, @Index + 1, 1,UPPER(SUBSTRING(@InputString, @Index + 1, 1)))\nEND\n SET @Index = @Index + 1\nEND\n\nRETURN ISNULL(@OutputString,'')\nEND\n</code></pre>\n\n<p>Test calls:</p>\n\n<pre><code>select dbo.fnConvert_TitleCase(Upper('ÄÄ ÖÖ ÜÜ ÉÉ ØØ ĈĈ ÆÆ')) as test\nselect dbo.fnConvert_TitleCase(upper('Whatever the mind of man can conceive and believe, it can achieve. – Napoleon hill')) as test\n</code></pre>\n\n<p>Results:</p>\n\n<p><img src=\"https://i.stack.imgur.com/BdUzW.jpg\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 31191399,
"author": "Kenjamarticus",
"author_id": 5074978,
"author_profile": "https://Stackoverflow.com/users/5074978",
"pm_score": 2,
"selected": false,
"text": "<p>If you're in SSIS importing data that has mixed cased and need to do a lookup on a column with proper case, you'll notice that the lookup fails where the source is mixed and the lookup source is proper. You'll also notice you can't use the right and left functions is SSIS for SQL Server 2008r2 for derived columns. Here's a solution that works for me: </p>\n\n<pre><code>UPPER(substring(input_column_name,1,1)) + LOWER(substring(input_column_name, 2, len(input_column_name)-1))\n</code></pre>\n"
},
{
"answer_id": 38646988,
"author": "Alansoft",
"author_id": 3281610,
"author_profile": "https://Stackoverflow.com/users/3281610",
"pm_score": 3,
"selected": false,
"text": "<p>I am a little late in the game, but I believe this is more functional and it works with any language, including Russian, German, Thai, Vietnamese etc.\nIt will make uppercase anything after ' or - or . or ( or ) or space (obviously :).</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnToProperCase]( @name nvarchar(500) )\nRETURNS nvarchar(500)\nAS\nBEGIN\ndeclare @pos int = 1\n , @pos2 int\n\nif (@name <> '')--or @name = lower(@name) collate SQL_Latin1_General_CP1_CS_AS or @name = upper(@name) collate SQL_Latin1_General_CP1_CS_AS)\nbegin\n set @name = lower(rtrim(@name))\n while (1 = 1)\n begin\n set @name = stuff(@name, @pos, 1, upper(substring(@name, @pos, 1)))\n set @pos2 = patindex('%[- ''.)(]%', substring(@name, @pos, 500))\n set @pos += @pos2\n if (isnull(@pos2, 0) = 0 or @pos > len(@name))\n break\n end\nend\n\nreturn @name\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 39394049,
"author": "Vorlic",
"author_id": 4248435,
"author_profile": "https://Stackoverflow.com/users/4248435",
"pm_score": -1,
"selected": false,
"text": "<p>I know the devil is in the detail (especially where people's personal data is concerned), and that it would be very nice to have properly capitalised names, but the above kind of hassle is why the pragmatic, time-conscious amongst us use the following: </p>\n\n<p><code>SELECT UPPER('Put YoUR O'So oddLy casED McWeird-nAme von rightHERE here')</code></p>\n\n<p>In my experience, people are fine seeing THEIR NAME ... even when it's half way through a sentence.</p>\n\n<p>Refer to: the Russians used a pencil!</p>\n"
},
{
"answer_id": 51403256,
"author": "FriskyKitty",
"author_id": 897184,
"author_profile": "https://Stackoverflow.com/users/897184",
"pm_score": 0,
"selected": false,
"text": "<p>Just learned about <code>InitCap()</code>. </p>\n\n<p>Here is some sample code:</p>\n\n<pre><code>SELECT ID\n ,InitCap(LastName ||', '|| FirstName ||' '|| Nvl(MiddleName,'')) AS RecipientName\nFROM SomeTable\n</code></pre>\n"
},
{
"answer_id": 51498901,
"author": "Sathish Babu",
"author_id": 10127962,
"author_profile": "https://Stackoverflow.com/users/10127962",
"pm_score": 0,
"selected": false,
"text": "<p>This worked in SSMS:</p>\n\n<pre><code>Select Jobtitle,\nconcat(Upper(LEFT(jobtitle,1)), SUBSTRING(jobtitle,2,LEN(jobtitle))) as Propercase\nFrom [HumanResources].[Employee]\n</code></pre>\n"
},
{
"answer_id": 53231234,
"author": "Gabe",
"author_id": 220997,
"author_profile": "https://Stackoverflow.com/users/220997",
"pm_score": 1,
"selected": false,
"text": "<p>Borrowed and improved on @Richard Sayakanit answer. This handles multiple words. Like his answer, this doesn't use any UDFs, only built-in functions (<code>STRING_SPLIT</code> and <code>STRING_AGG</code>) and it's pretty fast. <code>STRING_AGG</code> requires SQL Server 2017 but you can always use the <code>STUFF/XML</code> trick. Won't handle every exception but can work great for many requirements. </p>\n\n<pre><code>SELECT StateName = 'North Carolina' \nINTO #States\nUNION ALL\nSELECT 'Texas'\n\n\n;WITH cteData AS \n(\n SELECT \n UPPER(LEFT(value, 1)) +\n LOWER(RIGHT(value, LEN(value) - 1)) value, op.StateName\n FROM #States op\n CROSS APPLY STRING_SPLIT(op.StateName, ' ') AS ss\n)\nSELECT \n STRING_AGG(value, ' ')\nFROM cteData c \nGROUP BY StateName\n</code></pre>\n"
},
{
"answer_id": 54932265,
"author": "reggaeguitar",
"author_id": 2125444,
"author_profile": "https://Stackoverflow.com/users/2125444",
"pm_score": 1,
"selected": false,
"text": "<p>If you know all the data is just a single word here's a solution. First update the column to all lower and then run the following</p>\n\n<pre><code> update tableName set columnName = \n upper(SUBSTRING(columnName, 1, 1)) + substring(columnName, 2, len(columnName)) from tableName\n</code></pre>\n"
},
{
"answer_id": 55631111,
"author": "philipnye",
"author_id": 4659442,
"author_profile": "https://Stackoverflow.com/users/4659442",
"pm_score": 2,
"selected": false,
"text": "<p>A slight modification to @Galwegian's answer - which turns e.g. <code>St Elizabeth's</code> into <code>St Elizabeth'S</code>.</p>\n\n<p>This modification keeps apostrophe-s as lowercase where the s comes at the end of the string provided or the s is followed by a space (and only in those circumstances).</p>\n\n<pre><code>create function properCase(@text as varchar(8000))\nreturns varchar(8000)\nas\nbegin\n declare @reset int;\n declare @ret varchar(8000);\n declare @i int;\n declare @c char(1);\n declare @d char(1);\n\n if @text is null\n return null;\n\n select @reset = 1, @i = 1, @ret = '';\n\n while (@i <= len(@text))\n select\n @c = substring(@text, @i, 1),\n @d = substring(@text, @i+1, 1),\n @ret = @ret + case when @reset = 1 or (@reset=-1 and @c!='s') or (@reset=-1 and @c='s' and @d!=' ') then upper(@c) else lower(@c) end,\n @reset = case when @c like '[a-za-z]' then 0 when @c='''' then -1 else 1 end,\n @i = @i + 1\n return @ret\nend\n</code></pre>\n\n<p>It turns:</p>\n\n<ul>\n<li><code>st elizabeth's</code> into <code>St Elizabeth's</code></li>\n<li><code>o'keefe</code> into <code>O'Keefe</code></li>\n<li><code>o'sullivan</code> into <code>O'Sullivan</code></li>\n</ul>\n\n<p>Others' comments that different solutions are preferable for non-English input remain the case.</p>\n"
},
{
"answer_id": 58289601,
"author": "Zexks Marquise",
"author_id": 4205675,
"author_profile": "https://Stackoverflow.com/users/4205675",
"pm_score": 1,
"selected": false,
"text": "<p>Recently had to tackle this and came up with the following after nothing quite hit everything I wanted. This will do an entire sentence, cases for special word handling. We also had issues with single character 'words' that a lot of the simpler methods handle but not the more complicated methods. Single return variable, no loops or cursors either.</p>\n\n<pre><code>CREATE FUNCTION ProperCase(@Text AS NVARCHAR(MAX))\nRETURNS NVARCHAR(MAX)\nAS BEGIN\n\n DECLARE @return NVARCHAR(MAX)\n\n SELECT @return = COALESCE(@return + ' ', '') + Word FROM (\n SELECT CASE\n WHEN LOWER(value) = 'llc' THEN UPPER(value)\n WHEN LOWER(value) = 'lp' THEN UPPER(value) --Add as many new special cases as needed\n ELSE\n CASE WHEN LEN(value) = 1\n THEN UPPER(value)\n ELSE UPPER(LEFT(value, 1)) + (LOWER(RIGHT(value, LEN(value) - 1)))\n END\n END AS Word\n FROM STRING_SPLIT(@Text, ' ')\n ) tmp\n\n RETURN @return\nEND\n</code></pre>\n"
},
{
"answer_id": 60031227,
"author": "tobydodds",
"author_id": 4731066,
"author_profile": "https://Stackoverflow.com/users/4731066",
"pm_score": -1,
"selected": false,
"text": "<p>Copy and paste your data into MS Word and use built in text-conversion to \"Capitalize Each Word\". Compare against your original data to address exceptions. Can't see any way around manually sidestepping \"MacDonald\" and \"IBM\" type exceptions but this was how I got it done FWIW.</p>\n"
},
{
"answer_id": 64435946,
"author": "cryocaustik",
"author_id": 3931046,
"author_profile": "https://Stackoverflow.com/users/3931046",
"pm_score": 2,
"selected": false,
"text": "<p>On Server Server 2016 and newer, you can use <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">STRING_SPLIT</a></p>\n<pre class=\"lang-sql prettyprint-override\"><code>\nwith t as (\n select 'GOOFYEAR Tire and Rubber Company' as n\n union all\n select 'THE HAPPY BEAR' as n\n union all\n select 'MONK HOUSE SALES' as n\n union all\n select 'FORUM COMMUNICATIONS' as n\n)\nselect\n n,\n (\n select ' ' + (\n upper(left(value, 1))\n + lower(substring(value, 2, 999))\n )\n from (\n select value\n from string_split(t.n, ' ')\n ) as sq\n for xml path ('')\n ) as title_cased\nfrom t\n</code></pre>\n<h2><a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=97cc48b466d259ea8f599541646e4c4b\" rel=\"nofollow noreferrer\">Example</a></h2>\n"
},
{
"answer_id": 66825487,
"author": "JoshRoss",
"author_id": 81010,
"author_profile": "https://Stackoverflow.com/users/81010",
"pm_score": 0,
"selected": false,
"text": "<p>Sadly, I am proposing yet another function. This one seems faster than most, but only capitalizes the first letter of words separated by spaces. I've checked that the input is not null, and that it works if you have multiple spaces somewhere in the middle of the string. I'm cross applying the length function so I don't have to call it twice. I would have thought that SQL Server would have cached that value. Caveat emptor.</p>\n<pre><code>CREATE OR ALTER FUNCTION dbo.ProperCase(@value varchar(MAX)) RETURNS varchar(MAX) AS \n BEGIN\n \n RETURN (SELECT STRING_AGG(CASE lv WHEN 0 THEN '' WHEN 1 THEN UPPER(value) \n ELSE UPPER(LEFT(value,1)) + LOWER(RIGHT(value,lv-1)) END,' ') \n FROM STRING_SPLIT(TRIM(@value),' ') AS ss \n CROSS APPLY (SELECT LEN(VALUE) lv) AS reuse \n WHERE @value IS NOT NULL)\n\n END\n</code></pre>\n"
},
{
"answer_id": 69184214,
"author": "Joe Shakely",
"author_id": 7537658,
"author_profile": "https://Stackoverflow.com/users/7537658",
"pm_score": 0,
"selected": false,
"text": "<h3>This function has worked for me</h3>\n<pre><code>create function [dbo].Pascal (@string varchar(max))\nreturns varchar(max)\nas\nbegin\n declare @Index int\n ,@ResultString varchar(max)\n\n set @Index = 1\n set @ResultString = ''\n\n while (@Index < LEN(@string) + 1)\n begin\n if (@Index = 1)\n begin\n set @ResultString += UPPER(SUBSTRING(@string, @Index, 1))\n set @Index += 1\n end\n else if (\n (\n SUBSTRING(@string, @Index - 1, 1) = ' '\n or SUBSTRING(@string, @Index - 1, 1) = '-'\n or SUBSTRING(@string, @Index + 1, 1) = '-'\n )\n and @Index + 1 <> LEN(@string) + 1\n )\n begin\n set @ResultString += UPPER(SUBSTRING(@string, @Index, 1))\n set @Index += 1\n end\n else\n begin\n set @ResultString += LOWER(SUBSTRING(@string, @Index, 1))\n set @Index += 1\n end\n end\n\n if (@@ERROR <> 0)\n begin\n set @ResultString = @string\n end\n\n return replace(replace(replace(@ResultString, ' ii', ' II'), ' iii', ' III'), ' iv', ' IV')\nend\n</code></pre>\n"
},
{
"answer_id": 74368743,
"author": "David Zayn",
"author_id": 8697724,
"author_profile": "https://Stackoverflow.com/users/8697724",
"pm_score": 1,
"selected": false,
"text": "<p>In Oracle SQL or PostgreSQL, just do:</p>\n<pre><code>SELECT INITCAP(title) FROM data;\n</code></pre>\n<p>In SQL Server, define the function first as in below, then:</p>\n<pre><code>SELECT dbo.InitCap(title) FROM data;\n</code></pre>\n<p>Define dbo.InitCap():</p>\n<pre><code> -- Drop the function if it already exists\n IF OBJECT_ID('dbo.InitCap') IS NOT NULL\n DROP FUNCTION dbo.InitCap;\n GO\n \n -- Implementing Oracle INITCAP function\n CREATE FUNCTION dbo.InitCap (@inStr VARCHAR(8000))\n RETURNS VARCHAR(8000)\n AS\n BEGIN\n DECLARE @outStr VARCHAR(8000) = LOWER(@inStr),\n @char CHAR(1), \n @alphanum BIT = 0,\n @len INT = LEN(@inStr),\n @pos INT = 1; \n \n -- Iterate through all characters in the input string\n WHILE @pos <= @len BEGIN\n \n -- Get the next character\n SET @char = SUBSTRING(@inStr, @pos, 1);\n \n -- If the position is first, or the previous characater is not alphanumeric\n -- convert the current character to upper case\n IF @pos = 1 OR @alphanum = 0\n SET @outStr = STUFF(@outStr, @pos, 1, UPPER(@char));\n \n SET @pos = @pos + 1;\n \n -- Define if the current character is non-alphanumeric\n IF ASCII(@char) <= 47 OR (ASCII(@char) BETWEEN 58 AND 64) OR\n (ASCII(@char) BETWEEN 91 AND 96) OR (ASCII(@char) BETWEEN 123 AND 126)\n SET @alphanum = 0;\n ELSE\n SET @alphanum = 1;\n \n END\n \n RETURN @outStr; \n END\n GO\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
] |
I have a table that was imported as all UPPER CASE and I would like to turn it into Proper Case. What script have any of you used to complete this?
|
Here's a UDF that will do the trick...
```
create function ProperCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
declare @Reset bit;
declare @Ret varchar(8000);
declare @i int;
declare @c char(1);
if @Text is null
return null;
select @Reset = 1, @i = 1, @Ret = '';
while (@i <= len(@Text))
select @c = substring(@Text, @i, 1),
@Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,
@Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
@i = @i + 1
return @Ret
end
```
You will still have to use it to update your data though.
|
230,150 |
<p>Visual Studio 2008 w/Sp1</p>
<p>To reproduce my problem I simply create a new .Net 2.0 web application and add a page with the following markup:</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication5._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:button id="button1" runat="server" />
</div>
</form>
</body>
</html>
</code></pre>
<p>what happens is that a line is drawn under :button with the statement "Validation (): Element 'button' is not supported."</p>
<p>I've tried repairing the .net framework; however, that had no impact. This started happening on two different machines, one is vista the other is XP within the past week.</p>
<p><strong>UPDATE:</strong> I closed this question because after spending 2 days trying to fix it I gave up and performed a complete reinstall of Visual Studio 2008. This resolved whatever was jacked up and now the machines in question work properly. I upvoted each of you for the help.</p>
|
[
{
"answer_id": 230177,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 8,
"selected": true,
"text": "<p>Here's a UDF that will do the trick...</p>\n\n<pre><code>create function ProperCase(@Text as varchar(8000))\nreturns varchar(8000)\nas\nbegin\n declare @Reset bit;\n declare @Ret varchar(8000);\n declare @i int;\n declare @c char(1);\n\n if @Text is null\n return null;\n\n select @Reset = 1, @i = 1, @Ret = '';\n\n while (@i <= len(@Text))\n select @c = substring(@Text, @i, 1),\n @Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,\n @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,\n @i = @i + 1\n return @Ret\nend\n</code></pre>\n\n<p>You will still have to use it to update your data though.</p>\n"
},
{
"answer_id": 230224,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 7,
"selected": false,
"text": "<p>This function:</p>\n\n<ul>\n<li>\"Proper Cases\" all \"UPPER CASE\" words that are delimited by white space</li>\n<li>leaves \"lower case words\" alone</li>\n<li>works properly even for non-English alphabets</li>\n<li>is portable in that it does not use fancy features of recent SQL server versions</li>\n<li>can be easily changed to use NCHAR and NVARCHAR for unicode support,as well as any parameter length you see fit</li>\n<li>white space definition can be configured</li>\n</ul>\n\n\n\n<pre><code>CREATE FUNCTION ToProperCase(@string VARCHAR(255)) RETURNS VARCHAR(255)\nAS\nBEGIN\n DECLARE @i INT -- index\n DECLARE @l INT -- input length\n DECLARE @c NCHAR(1) -- current char\n DECLARE @f INT -- first letter flag (1/0)\n DECLARE @o VARCHAR(255) -- output string\n DECLARE @w VARCHAR(10) -- characters considered as white space\n\n SET @w = '[' + CHAR(13) + CHAR(10) + CHAR(9) + CHAR(160) + ' ' + ']'\n SET @i = 1\n SET @l = LEN(@string)\n SET @f = 1\n SET @o = ''\n\n WHILE @i <= @l\n BEGIN\n SET @c = SUBSTRING(@string, @i, 1)\n IF @f = 1 \n BEGIN\n SET @o = @o + @c\n SET @f = 0\n END\n ELSE\n BEGIN\n SET @o = @o + LOWER(@c)\n END\n\n IF @c LIKE @w SET @f = 1\n\n SET @i = @i + 1\n END\n\n RETURN @o\nEND\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>dbo.ToProperCase('ALL UPPER CASE and SOME lower ÄÄ ÖÖ ÜÜ ÉÉ ØØ ĈĈ ÆÆ')\n-----------------------------------------------------------------\nAll Upper Case and Some lower Ää Öö Üü Éé Øø Cc Ææ\n</code></pre>\n"
},
{
"answer_id": 230290,
"author": "Cervo",
"author_id": 16219,
"author_profile": "https://Stackoverflow.com/users/16219",
"pm_score": 0,
"selected": false,
"text": "<p>I think you will find that the following is more efficient:</p>\n\n<pre><code>IF OBJECT_ID('dbo.ProperCase') IS NOT NULL\n DROP FUNCTION dbo.ProperCase\nGO\nCREATE FUNCTION dbo.PROPERCASE (\n @str VARCHAR(8000))\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n SET @str = ' ' + @str\n SET @str = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @str, ' a', ' A'), ' b', ' B'), ' c', ' C'), ' d', ' D'), ' e', ' E'), ' f', ' F'), ' g', ' G'), ' h', ' H'), ' i', ' I'), ' j', ' J'), ' k', ' K'), ' l', ' L'), ' m', ' M'), ' n', ' N'), ' o', ' O'), ' p', ' P'), ' q', ' Q'), ' r', ' R'), ' s', ' S'), ' t', ' T'), ' u', ' U'), ' v', ' V'), ' w', ' W'), ' x', ' X'), ' y', ' Y'), ' z', ' Z')\n RETURN RIGHT(@str, LEN(@str) - 1)\nEND\nGO\n</code></pre>\n\n<p>The replace statement could be cut and pasted directly into a SQL query. It is ultra ugly, however by replacing @str with the column you are interested in, you will not pay a price for an implicit cursor like you will with the udfs thus posted. I find that even using my UDF it is much more efficient.</p>\n\n<p>Oh and instead of generating the replace statement by hand use this:</p>\n\n<pre><code>-- Code Generator for expression\nDECLARE @x INT,\n @c CHAR(1),\n @sql VARCHAR(8000)\nSET @x = 0\nSET @sql = '@str' -- actual variable/column you want to replace\nWHILE @x < 26\nBEGIN\n SET @c = CHAR(ASCII('a') + @x)\n SET @sql = 'REPLACE(' + @sql + ', '' ' + @c+ ''', '' ' + UPPER(@c) + ''')'\n SET @x = @x + 1\nEND\nPRINT @sql\n</code></pre>\n\n<p>Anyway it depends on the number of rows. I wish you could just do s/\\b([a-z])/uc $1/, but oh well we work with the tools we have.</p>\n\n<p>NOTE you would have to use this as you would have to use it as....SELECT dbo.ProperCase(LOWER(column)) since the column is in uppercase. It actually works pretty fast on my table of 5,000 entries (not even one second) even with the lower.</p>\n\n<p>In response to the flurry of comments regarding internationalization I present the following implementation that handles every ascii character relying only on SQL Server's Implementation of upper and lower. Remember, the variables we are using here are VARCHAR which means that they can only hold ASCII values. In order to use further international alphabets, you have to use NVARCHAR. The logic would be similar but you would need to use UNICODE and NCHAR in place of ASCII AND CHAR and the replace statement would be much more huge....</p>\n\n<pre><code>-- Code Generator for expression\nDECLARE @x INT,\n @c CHAR(1),\n @sql VARCHAR(8000),\n @count INT\nSEt @x = 0\nSET @count = 0\nSET @sql = '@str' -- actual variable you want to replace\nWHILE @x < 256\nBEGIN\n SET @c = CHAR(@x)\n -- Only generate replacement expression for characters where upper and lowercase differ\n IF @x = ASCII(LOWER(@c)) AND @x != ASCII(UPPER(@c))\n BEGIN\n SET @sql = 'REPLACE(' + @sql + ', '' ' + @c+ ''', '' ' + UPPER(@c) + ''')'\n SET @count = @count + 1\n END\n SET @x = @x + 1\nEND\nPRINT @sql\nPRINT 'Total characters substituted: ' + CONVERT(VARCHAR(255), @count)\n</code></pre>\n\n<p>Basically the premise of the my method is trading pre-computing for efficiency. The full ASCII implementation is as follows:</p>\n\n<pre><code>IF OBJECT_ID('dbo.ProperCase') IS NOT NULL\n DROP FUNCTION dbo.ProperCase\nGO\nCREATE FUNCTION dbo.PROPERCASE (\n @str VARCHAR(8000))\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n SET @str = ' ' + @str\nSET @str = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@str, ' a', ' A'), ' b', ' B'), ' c', ' C'), ' d', ' D'), ' e', ' E'), ' f', ' F'), ' g', ' G'), ' h', ' H'), ' i', ' I'), ' j', ' J'), ' k', ' K'), ' l', ' L'), ' m', ' M'), ' n', ' N'), ' o', ' O'), ' p', ' P'), ' q', ' Q'), ' r', ' R'), ' s', ' S'), ' t', ' T'), ' u', ' U'), ' v', ' V'), ' w', ' W'), ' x', ' X'), ' y', ' Y'), ' z', ' Z'), ' š', ' Š'), ' œ', ' Œ'), ' ž', ' Ž'), ' à', ' À'), ' á', ' Á'), ' â', ' Â'), ' ã', ' Ã'), ' ä', ' Ä'), ' å', ' Å'), ' æ', ' Æ'), ' ç', ' Ç'), ' è', ' È'), ' é', ' É'), ' ê', ' Ê'), ' ë', ' Ë'), ' ì', ' Ì'), ' í', ' Í'), ' î', ' Î'), ' ï', ' Ï'), ' ð', ' Ð'), ' ñ', ' Ñ'), ' ò', ' Ò'), ' ó', ' Ó'), ' ô', ' Ô'), ' õ', ' Õ'), ' ö', ' Ö'), ' ø', ' Ø'), ' ù', ' Ù'), ' ú', ' Ú'), ' û', ' Û'), ' ü', ' Ü'), ' ý', ' Ý'), ' þ', ' Þ'), ' ÿ', ' Ÿ')\n RETURN RIGHT(@str, LEN(@str) - 1)\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 230693,
"author": "Toybuilder",
"author_id": 22329,
"author_profile": "https://Stackoverflow.com/users/22329",
"pm_score": 0,
"selected": false,
"text": "<p>Is it too late to go back and get the un-uppercased data? </p>\n\n<p>The von Neumann's, McCain's, DeGuzman's, and the Johnson-Smith's of your client base may not like the result of your processing...</p>\n\n<p>Also, I'm guessing that this is intended to be a one-time upgrade of the data? It might be easier to export, filter/modify, and re-import the corrected names into the db, and then you can use non-SQL approaches to name fixing...</p>\n"
},
{
"answer_id": 231705,
"author": "nathan_jr",
"author_id": 3769,
"author_profile": "https://Stackoverflow.com/users/3769",
"pm_score": 1,
"selected": false,
"text": "<p>The link I posted above is a great option that addresses the main issue: that we can never programmatically account for all cases (Smith-Jones, von Haussen, John Smith M.D.), at least not in an elegant manner. Tony introduces the concept of an exception / break character to deal with these cases.\nAnyways, building on Cervo's idea (upper all lower chars preceded by space), the replace statements could be wrapped up in a single table based replace instead. Really, any low/up character combination could be inserted into @alpha and the statement would not change: </p>\n\n<pre><code>declare @str nvarchar(8000)\ndeclare @alpha table (low nchar(1), up nchar(1))\n\n\nset @str = 'ALL UPPER CASE and SOME lower ÄÄ ÖÖ ÜÜ ÉÉ ØØ ĈĈ ÆÆ'\n\n-- stage the alpha (needs number table)\ninsert into @alpha\n -- A-Z / a-z\n select nchar(n+32),\n nchar(n)\n from dbo.Number\n where n between 65 and 90 or\n n between 192 and 223\n\n-- append space at start of str\nset @str = lower(' ' + @str)\n\n-- upper all lower case chars preceded by space\nselect @str = replace(@str, ' ' + low, ' ' + up) \nfrom @Alpha\n\nselect @str\n</code></pre>\n"
},
{
"answer_id": 231728,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": false,
"text": "<p>If you can enable the CLR in SQL Server (requires 2005 or later) then you could <a href=\"http://msdn.microsoft.com/en-us/library/w2kae45k.aspx\" rel=\"noreferrer\">create a CLR function</a> that uses the <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx\" rel=\"noreferrer\">TextInfo.ToTitleCase built-in function</a> which would allow you to create a culture-aware way of doing this in only a few lines of code.</p>\n"
},
{
"answer_id": 1007802,
"author": "Merritt",
"author_id": 60385,
"author_profile": "https://Stackoverflow.com/users/60385",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another variation I found on the SQLTeam.com Forums @\n<a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47718\" rel=\"nofollow noreferrer\">http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47718</a></p>\n\n<pre><code>create FUNCTION PROPERCASE\n(\n--The string to be converted to proper case\n@input varchar(8000)\n)\n--This function returns the proper case string of varchar type\nRETURNS varchar(8000)\nAS\nBEGIN\nIF @input IS NULL\nBEGIN\n--Just return NULL if input string is NULL\nRETURN NULL\nEND\n\n--Character variable declarations\nDECLARE @output varchar(8000)\n--Integer variable declarations\nDECLARE @ctr int, @len int, @found_at int\n--Constant declarations\nDECLARE @LOWER_CASE_a int, @LOWER_CASE_z int, @Delimiter char(3), @UPPER_CASE_A int, @UPPER_CASE_Z int\n\n--Variable/Constant initializations\nSET @ctr = 1\nSET @len = LEN(@input)\nSET @output = ''\nSET @LOWER_CASE_a = 97\nSET @LOWER_CASE_z = 122\nSET @Delimiter = ' ,-'\nSET @UPPER_CASE_A = 65\nSET @UPPER_CASE_Z = 90\n\nWHILE @ctr <= @len\nBEGIN\n--This loop will take care of reccuring white spaces\nWHILE CHARINDEX(SUBSTRING(@input,@ctr,1), @Delimiter) > 0\nBEGIN\nSET @output = @output + SUBSTRING(@input,@ctr,1)\nSET @ctr = @ctr + 1\nEND\n\nIF ASCII(SUBSTRING(@input,@ctr,1)) BETWEEN @LOWER_CASE_a AND @LOWER_CASE_z\nBEGIN\n--Converting the first character to upper case\nSET @output = @output + UPPER(SUBSTRING(@input,@ctr,1))\nEND\nELSE\nBEGIN\nSET @output = @output + SUBSTRING(@input,@ctr,1)\nEND\n\nSET @ctr = @ctr + 1\n\nWHILE CHARINDEX(SUBSTRING(@input,@ctr,1), @Delimiter) = 0 AND (@ctr <= @len)\nBEGIN\nIF ASCII(SUBSTRING(@input,@ctr,1)) BETWEEN @UPPER_CASE_A AND @UPPER_CASE_Z\nBEGIN\nSET @output = @output + LOWER(SUBSTRING(@input,@ctr,1))\nEND\nELSE\nBEGIN\nSET @output = @output + SUBSTRING(@input,@ctr,1)\nEND\nSET @ctr = @ctr + 1\nEND\n\nEND\nRETURN @output\nEND\n\n\n\nGO\nSET QUOTED_IDENTIFIER OFF\nGO\nSET ANSI_NULLS ON\nGO\n</code></pre>\n"
},
{
"answer_id": 1764042,
"author": "Dennis Allen",
"author_id": 214691,
"author_profile": "https://Stackoverflow.com/users/214691",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a version that uses a sequence or numbers table rather than a loop. You can modify the WHERE clause to suite your personal rules for when to convert a character to upper case. I have just included a simple set that will upper case any letter that is proceeded by a non-letter with the exception of apostrophes. This does how ever mean that 123apple would have a match on the \"a\" because \"3\" is not a letter. If you want just white-space (space, tab, carriage-return, line-feed), you can replace the pattern <code>'[^a-z]'</code> with <code>'[' + Char(32) + Char(9) + Char(13) + Char(10) + ']'</code>.</p>\n\n<hr>\n\n<pre><code>CREATE FUNCTION String.InitCap( @string nvarchar(4000) ) RETURNS nvarchar(4000) AS\nBEGIN\n\n-- 1. Convert all letters to lower case\n DECLARE @InitCap nvarchar(4000); SET @InitCap = Lower(@string);\n\n-- 2. Using a Sequence, replace the letters that should be upper case with their upper case version\n SELECT @InitCap = Stuff( @InitCap, n, 1, Upper( SubString( @InitCap, n, 1 ) ) )\n FROM (\n SELECT (1 + n1.n + n10.n + n100.n + n1000.n) AS n\n FROM (SELECT 0 AS n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS n1\n CROSS JOIN (SELECT 0 AS n UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40 UNION SELECT 50 UNION SELECT 60 UNION SELECT 70 UNION SELECT 80 UNION SELECT 90) AS n10\n CROSS JOIN (SELECT 0 AS n UNION SELECT 100 UNION SELECT 200 UNION SELECT 300 UNION SELECT 400 UNION SELECT 500 UNION SELECT 600 UNION SELECT 700 UNION SELECT 800 UNION SELECT 900) AS n100\n CROSS JOIN (SELECT 0 AS n UNION SELECT 1000 UNION SELECT 2000 UNION SELECT 3000) AS n1000\n ) AS Sequence\n WHERE \n n BETWEEN 1 AND Len( @InitCap )\n AND SubString( @InitCap, n, 1 ) LIKE '[a-z]' /* this character is a letter */\n AND (\n n = 1 /* this character is the first `character` */\n OR SubString( @InitCap, n-1, 1 ) LIKE '[^a-z]' /* the previous character is NOT a letter */\n )\n AND (\n n < 3 /* only test the 3rd or greater characters for this exception */\n OR SubString( @InitCap, n-2, 3 ) NOT LIKE '[a-z]''[a-z]' /* exception: The pattern <letter>'<letter> should not capatolize the letter following the apostrophy */\n )\n\n-- 3. Return the modified version of the input\n RETURN @InitCap\n\nEND\n</code></pre>\n"
},
{
"answer_id": 6602923,
"author": "Lee",
"author_id": 832403,
"author_profile": "https://Stackoverflow.com/users/832403",
"pm_score": 1,
"selected": false,
"text": "<p>It would make sense to maintain a lookup of exceptions to take care of The von Neumann's, McCain's, DeGuzman's, and the Johnson-Smith's.</p>\n"
},
{
"answer_id": 20660732,
"author": "Richard Sayakanit",
"author_id": 302589,
"author_profile": "https://Stackoverflow.com/users/302589",
"pm_score": 6,
"selected": false,
"text": "<pre><code>UPDATE titles\n SET title =\n UPPER(LEFT(title, 1)) +\n LOWER(RIGHT(title, LEN(title) - 1))\n</code></pre>\n\n<p><a href=\"http://sqlmag.com/t-sql/how-title-case-column-value\" rel=\"noreferrer\">http://sqlmag.com/t-sql/how-title-case-column-value</a></p>\n"
},
{
"answer_id": 28712621,
"author": "Harmeet Singh Bhamra",
"author_id": 2758965,
"author_profile": "https://Stackoverflow.com/users/2758965",
"pm_score": 4,
"selected": false,
"text": "<p>I know this is late post in this thread but, worth looking. This function works for me ever time. So thought of sharing it.</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnConvert_TitleCase] (@InputString VARCHAR(4000) )\nRETURNS VARCHAR(4000)\nAS\nBEGIN\nDECLARE @Index INT\nDECLARE @Char CHAR(1)\nDECLARE @OutputString VARCHAR(255)\n\nSET @OutputString = LOWER(@InputString)\nSET @Index = 2\nSET @OutputString = STUFF(@OutputString, 1, 1,UPPER(SUBSTRING(@InputString,1,1)))\n\nWHILE @Index <= LEN(@InputString)\nBEGIN\n SET @Char = SUBSTRING(@InputString, @Index, 1)\n IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&','''','(')\n IF @Index + 1 <= LEN(@InputString)\nBEGIN\n IF @Char != ''''\n OR\n UPPER(SUBSTRING(@InputString, @Index + 1, 1)) != 'S'\n SET @OutputString =\n STUFF(@OutputString, @Index + 1, 1,UPPER(SUBSTRING(@InputString, @Index + 1, 1)))\nEND\n SET @Index = @Index + 1\nEND\n\nRETURN ISNULL(@OutputString,'')\nEND\n</code></pre>\n\n<p>Test calls:</p>\n\n<pre><code>select dbo.fnConvert_TitleCase(Upper('ÄÄ ÖÖ ÜÜ ÉÉ ØØ ĈĈ ÆÆ')) as test\nselect dbo.fnConvert_TitleCase(upper('Whatever the mind of man can conceive and believe, it can achieve. – Napoleon hill')) as test\n</code></pre>\n\n<p>Results:</p>\n\n<p><img src=\"https://i.stack.imgur.com/BdUzW.jpg\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 31191399,
"author": "Kenjamarticus",
"author_id": 5074978,
"author_profile": "https://Stackoverflow.com/users/5074978",
"pm_score": 2,
"selected": false,
"text": "<p>If you're in SSIS importing data that has mixed cased and need to do a lookup on a column with proper case, you'll notice that the lookup fails where the source is mixed and the lookup source is proper. You'll also notice you can't use the right and left functions is SSIS for SQL Server 2008r2 for derived columns. Here's a solution that works for me: </p>\n\n<pre><code>UPPER(substring(input_column_name,1,1)) + LOWER(substring(input_column_name, 2, len(input_column_name)-1))\n</code></pre>\n"
},
{
"answer_id": 38646988,
"author": "Alansoft",
"author_id": 3281610,
"author_profile": "https://Stackoverflow.com/users/3281610",
"pm_score": 3,
"selected": false,
"text": "<p>I am a little late in the game, but I believe this is more functional and it works with any language, including Russian, German, Thai, Vietnamese etc.\nIt will make uppercase anything after ' or - or . or ( or ) or space (obviously :).</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnToProperCase]( @name nvarchar(500) )\nRETURNS nvarchar(500)\nAS\nBEGIN\ndeclare @pos int = 1\n , @pos2 int\n\nif (@name <> '')--or @name = lower(@name) collate SQL_Latin1_General_CP1_CS_AS or @name = upper(@name) collate SQL_Latin1_General_CP1_CS_AS)\nbegin\n set @name = lower(rtrim(@name))\n while (1 = 1)\n begin\n set @name = stuff(@name, @pos, 1, upper(substring(@name, @pos, 1)))\n set @pos2 = patindex('%[- ''.)(]%', substring(@name, @pos, 500))\n set @pos += @pos2\n if (isnull(@pos2, 0) = 0 or @pos > len(@name))\n break\n end\nend\n\nreturn @name\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 39394049,
"author": "Vorlic",
"author_id": 4248435,
"author_profile": "https://Stackoverflow.com/users/4248435",
"pm_score": -1,
"selected": false,
"text": "<p>I know the devil is in the detail (especially where people's personal data is concerned), and that it would be very nice to have properly capitalised names, but the above kind of hassle is why the pragmatic, time-conscious amongst us use the following: </p>\n\n<p><code>SELECT UPPER('Put YoUR O'So oddLy casED McWeird-nAme von rightHERE here')</code></p>\n\n<p>In my experience, people are fine seeing THEIR NAME ... even when it's half way through a sentence.</p>\n\n<p>Refer to: the Russians used a pencil!</p>\n"
},
{
"answer_id": 51403256,
"author": "FriskyKitty",
"author_id": 897184,
"author_profile": "https://Stackoverflow.com/users/897184",
"pm_score": 0,
"selected": false,
"text": "<p>Just learned about <code>InitCap()</code>. </p>\n\n<p>Here is some sample code:</p>\n\n<pre><code>SELECT ID\n ,InitCap(LastName ||', '|| FirstName ||' '|| Nvl(MiddleName,'')) AS RecipientName\nFROM SomeTable\n</code></pre>\n"
},
{
"answer_id": 51498901,
"author": "Sathish Babu",
"author_id": 10127962,
"author_profile": "https://Stackoverflow.com/users/10127962",
"pm_score": 0,
"selected": false,
"text": "<p>This worked in SSMS:</p>\n\n<pre><code>Select Jobtitle,\nconcat(Upper(LEFT(jobtitle,1)), SUBSTRING(jobtitle,2,LEN(jobtitle))) as Propercase\nFrom [HumanResources].[Employee]\n</code></pre>\n"
},
{
"answer_id": 53231234,
"author": "Gabe",
"author_id": 220997,
"author_profile": "https://Stackoverflow.com/users/220997",
"pm_score": 1,
"selected": false,
"text": "<p>Borrowed and improved on @Richard Sayakanit answer. This handles multiple words. Like his answer, this doesn't use any UDFs, only built-in functions (<code>STRING_SPLIT</code> and <code>STRING_AGG</code>) and it's pretty fast. <code>STRING_AGG</code> requires SQL Server 2017 but you can always use the <code>STUFF/XML</code> trick. Won't handle every exception but can work great for many requirements. </p>\n\n<pre><code>SELECT StateName = 'North Carolina' \nINTO #States\nUNION ALL\nSELECT 'Texas'\n\n\n;WITH cteData AS \n(\n SELECT \n UPPER(LEFT(value, 1)) +\n LOWER(RIGHT(value, LEN(value) - 1)) value, op.StateName\n FROM #States op\n CROSS APPLY STRING_SPLIT(op.StateName, ' ') AS ss\n)\nSELECT \n STRING_AGG(value, ' ')\nFROM cteData c \nGROUP BY StateName\n</code></pre>\n"
},
{
"answer_id": 54932265,
"author": "reggaeguitar",
"author_id": 2125444,
"author_profile": "https://Stackoverflow.com/users/2125444",
"pm_score": 1,
"selected": false,
"text": "<p>If you know all the data is just a single word here's a solution. First update the column to all lower and then run the following</p>\n\n<pre><code> update tableName set columnName = \n upper(SUBSTRING(columnName, 1, 1)) + substring(columnName, 2, len(columnName)) from tableName\n</code></pre>\n"
},
{
"answer_id": 55631111,
"author": "philipnye",
"author_id": 4659442,
"author_profile": "https://Stackoverflow.com/users/4659442",
"pm_score": 2,
"selected": false,
"text": "<p>A slight modification to @Galwegian's answer - which turns e.g. <code>St Elizabeth's</code> into <code>St Elizabeth'S</code>.</p>\n\n<p>This modification keeps apostrophe-s as lowercase where the s comes at the end of the string provided or the s is followed by a space (and only in those circumstances).</p>\n\n<pre><code>create function properCase(@text as varchar(8000))\nreturns varchar(8000)\nas\nbegin\n declare @reset int;\n declare @ret varchar(8000);\n declare @i int;\n declare @c char(1);\n declare @d char(1);\n\n if @text is null\n return null;\n\n select @reset = 1, @i = 1, @ret = '';\n\n while (@i <= len(@text))\n select\n @c = substring(@text, @i, 1),\n @d = substring(@text, @i+1, 1),\n @ret = @ret + case when @reset = 1 or (@reset=-1 and @c!='s') or (@reset=-1 and @c='s' and @d!=' ') then upper(@c) else lower(@c) end,\n @reset = case when @c like '[a-za-z]' then 0 when @c='''' then -1 else 1 end,\n @i = @i + 1\n return @ret\nend\n</code></pre>\n\n<p>It turns:</p>\n\n<ul>\n<li><code>st elizabeth's</code> into <code>St Elizabeth's</code></li>\n<li><code>o'keefe</code> into <code>O'Keefe</code></li>\n<li><code>o'sullivan</code> into <code>O'Sullivan</code></li>\n</ul>\n\n<p>Others' comments that different solutions are preferable for non-English input remain the case.</p>\n"
},
{
"answer_id": 58289601,
"author": "Zexks Marquise",
"author_id": 4205675,
"author_profile": "https://Stackoverflow.com/users/4205675",
"pm_score": 1,
"selected": false,
"text": "<p>Recently had to tackle this and came up with the following after nothing quite hit everything I wanted. This will do an entire sentence, cases for special word handling. We also had issues with single character 'words' that a lot of the simpler methods handle but not the more complicated methods. Single return variable, no loops or cursors either.</p>\n\n<pre><code>CREATE FUNCTION ProperCase(@Text AS NVARCHAR(MAX))\nRETURNS NVARCHAR(MAX)\nAS BEGIN\n\n DECLARE @return NVARCHAR(MAX)\n\n SELECT @return = COALESCE(@return + ' ', '') + Word FROM (\n SELECT CASE\n WHEN LOWER(value) = 'llc' THEN UPPER(value)\n WHEN LOWER(value) = 'lp' THEN UPPER(value) --Add as many new special cases as needed\n ELSE\n CASE WHEN LEN(value) = 1\n THEN UPPER(value)\n ELSE UPPER(LEFT(value, 1)) + (LOWER(RIGHT(value, LEN(value) - 1)))\n END\n END AS Word\n FROM STRING_SPLIT(@Text, ' ')\n ) tmp\n\n RETURN @return\nEND\n</code></pre>\n"
},
{
"answer_id": 60031227,
"author": "tobydodds",
"author_id": 4731066,
"author_profile": "https://Stackoverflow.com/users/4731066",
"pm_score": -1,
"selected": false,
"text": "<p>Copy and paste your data into MS Word and use built in text-conversion to \"Capitalize Each Word\". Compare against your original data to address exceptions. Can't see any way around manually sidestepping \"MacDonald\" and \"IBM\" type exceptions but this was how I got it done FWIW.</p>\n"
},
{
"answer_id": 64435946,
"author": "cryocaustik",
"author_id": 3931046,
"author_profile": "https://Stackoverflow.com/users/3931046",
"pm_score": 2,
"selected": false,
"text": "<p>On Server Server 2016 and newer, you can use <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">STRING_SPLIT</a></p>\n<pre class=\"lang-sql prettyprint-override\"><code>\nwith t as (\n select 'GOOFYEAR Tire and Rubber Company' as n\n union all\n select 'THE HAPPY BEAR' as n\n union all\n select 'MONK HOUSE SALES' as n\n union all\n select 'FORUM COMMUNICATIONS' as n\n)\nselect\n n,\n (\n select ' ' + (\n upper(left(value, 1))\n + lower(substring(value, 2, 999))\n )\n from (\n select value\n from string_split(t.n, ' ')\n ) as sq\n for xml path ('')\n ) as title_cased\nfrom t\n</code></pre>\n<h2><a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=97cc48b466d259ea8f599541646e4c4b\" rel=\"nofollow noreferrer\">Example</a></h2>\n"
},
{
"answer_id": 66825487,
"author": "JoshRoss",
"author_id": 81010,
"author_profile": "https://Stackoverflow.com/users/81010",
"pm_score": 0,
"selected": false,
"text": "<p>Sadly, I am proposing yet another function. This one seems faster than most, but only capitalizes the first letter of words separated by spaces. I've checked that the input is not null, and that it works if you have multiple spaces somewhere in the middle of the string. I'm cross applying the length function so I don't have to call it twice. I would have thought that SQL Server would have cached that value. Caveat emptor.</p>\n<pre><code>CREATE OR ALTER FUNCTION dbo.ProperCase(@value varchar(MAX)) RETURNS varchar(MAX) AS \n BEGIN\n \n RETURN (SELECT STRING_AGG(CASE lv WHEN 0 THEN '' WHEN 1 THEN UPPER(value) \n ELSE UPPER(LEFT(value,1)) + LOWER(RIGHT(value,lv-1)) END,' ') \n FROM STRING_SPLIT(TRIM(@value),' ') AS ss \n CROSS APPLY (SELECT LEN(VALUE) lv) AS reuse \n WHERE @value IS NOT NULL)\n\n END\n</code></pre>\n"
},
{
"answer_id": 69184214,
"author": "Joe Shakely",
"author_id": 7537658,
"author_profile": "https://Stackoverflow.com/users/7537658",
"pm_score": 0,
"selected": false,
"text": "<h3>This function has worked for me</h3>\n<pre><code>create function [dbo].Pascal (@string varchar(max))\nreturns varchar(max)\nas\nbegin\n declare @Index int\n ,@ResultString varchar(max)\n\n set @Index = 1\n set @ResultString = ''\n\n while (@Index < LEN(@string) + 1)\n begin\n if (@Index = 1)\n begin\n set @ResultString += UPPER(SUBSTRING(@string, @Index, 1))\n set @Index += 1\n end\n else if (\n (\n SUBSTRING(@string, @Index - 1, 1) = ' '\n or SUBSTRING(@string, @Index - 1, 1) = '-'\n or SUBSTRING(@string, @Index + 1, 1) = '-'\n )\n and @Index + 1 <> LEN(@string) + 1\n )\n begin\n set @ResultString += UPPER(SUBSTRING(@string, @Index, 1))\n set @Index += 1\n end\n else\n begin\n set @ResultString += LOWER(SUBSTRING(@string, @Index, 1))\n set @Index += 1\n end\n end\n\n if (@@ERROR <> 0)\n begin\n set @ResultString = @string\n end\n\n return replace(replace(replace(@ResultString, ' ii', ' II'), ' iii', ' III'), ' iv', ' IV')\nend\n</code></pre>\n"
},
{
"answer_id": 74368743,
"author": "David Zayn",
"author_id": 8697724,
"author_profile": "https://Stackoverflow.com/users/8697724",
"pm_score": 1,
"selected": false,
"text": "<p>In Oracle SQL or PostgreSQL, just do:</p>\n<pre><code>SELECT INITCAP(title) FROM data;\n</code></pre>\n<p>In SQL Server, define the function first as in below, then:</p>\n<pre><code>SELECT dbo.InitCap(title) FROM data;\n</code></pre>\n<p>Define dbo.InitCap():</p>\n<pre><code> -- Drop the function if it already exists\n IF OBJECT_ID('dbo.InitCap') IS NOT NULL\n DROP FUNCTION dbo.InitCap;\n GO\n \n -- Implementing Oracle INITCAP function\n CREATE FUNCTION dbo.InitCap (@inStr VARCHAR(8000))\n RETURNS VARCHAR(8000)\n AS\n BEGIN\n DECLARE @outStr VARCHAR(8000) = LOWER(@inStr),\n @char CHAR(1), \n @alphanum BIT = 0,\n @len INT = LEN(@inStr),\n @pos INT = 1; \n \n -- Iterate through all characters in the input string\n WHILE @pos <= @len BEGIN\n \n -- Get the next character\n SET @char = SUBSTRING(@inStr, @pos, 1);\n \n -- If the position is first, or the previous characater is not alphanumeric\n -- convert the current character to upper case\n IF @pos = 1 OR @alphanum = 0\n SET @outStr = STUFF(@outStr, @pos, 1, UPPER(@char));\n \n SET @pos = @pos + 1;\n \n -- Define if the current character is non-alphanumeric\n IF ASCII(@char) <= 47 OR (ASCII(@char) BETWEEN 58 AND 64) OR\n (ASCII(@char) BETWEEN 91 AND 96) OR (ASCII(@char) BETWEEN 123 AND 126)\n SET @alphanum = 0;\n ELSE\n SET @alphanum = 1;\n \n END\n \n RETURN @outStr; \n END\n GO\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2424/"
] |
Visual Studio 2008 w/Sp1
To reproduce my problem I simply create a new .Net 2.0 web application and add a page with the following markup:
```
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication5._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:button id="button1" runat="server" />
</div>
</form>
</body>
</html>
```
what happens is that a line is drawn under :button with the statement "Validation (): Element 'button' is not supported."
I've tried repairing the .net framework; however, that had no impact. This started happening on two different machines, one is vista the other is XP within the past week.
**UPDATE:** I closed this question because after spending 2 days trying to fix it I gave up and performed a complete reinstall of Visual Studio 2008. This resolved whatever was jacked up and now the machines in question work properly. I upvoted each of you for the help.
|
Here's a UDF that will do the trick...
```
create function ProperCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
declare @Reset bit;
declare @Ret varchar(8000);
declare @i int;
declare @c char(1);
if @Text is null
return null;
select @Reset = 1, @i = 1, @Ret = '';
while (@i <= len(@Text))
select @c = substring(@Text, @i, 1),
@Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,
@Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
@i = @i + 1
return @Ret
end
```
You will still have to use it to update your data though.
|
230,186 |
<p>I am trying to aid another programmer with a page called Default.aspx with a code-behind section, and unfortunately I am at a bit of a loss.</p>
<pre><code> Partial Class _Default
Inherits OverheadClass
'A bunch of global variables here'
Private Sub page_load(ByVal sender As Object, ByVal e As System.Eventarts) Handles Me.Load
'Function goes here'
</code></pre>
<p>And in the OverheadClass we have</p>
<pre><code> Public Sub Sub_OverheadClass_Load(ByVal sender As Object, ByVal e as System.EventArgs) Handles MyClass.Load
</code></pre>
<p>The desired effect is when the OverheadClass is inherited, we want its load to run before the load event on the page runs. There is probably a very simple answer to this that I am missing.</p>
<p>Edit: I forgot to note that we write in VB, and not C# as many of you are used to for ASP.</p>
|
[
{
"answer_id": 230200,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 5,
"selected": true,
"text": "<p>You should be able to override the OnLoad and call the base class's OnLoad first, then your class, for example:</p>\n\n<p>C# Version</p>\n\n<pre><code>protected override void OnLoad(EventArgs e)\n{\n base.OnLoad(e);\n\n // Do some stuff here\n}\n</code></pre>\n\n<p>VB Version</p>\n\n<pre><code>Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)\n\n MyBase.OnLoad(e)\n\n ' Do some stuff here\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 230217,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 2,
"selected": false,
"text": "<p>In VB it would be:</p>\n\n<pre><code>Private Sub page_load(ByVal sender As Object, ByVal e As System.Eventarts) Handles Me.Load\n Mybase.Sub_OverheadClass_Load(e)\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 230363,
"author": "Loscas",
"author_id": 22706,
"author_profile": "https://Stackoverflow.com/users/22706",
"pm_score": 0,
"selected": false,
"text": "<p>Your default page should inherit OverheadClass</p>\n\n<pre><code> Partial Public Class _Default\n Inherits OverheadClass\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n 'Do some page stuff'\n End Sub\n End Class\n</code></pre>\n\n<p>And OverheadClass should inherit System.Web.UI.Page</p>\n\n<pre><code>Public Class OverheadClass\n Inherits System.Web.UI.Page\n Public Sub Sub_OverheadClass_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyClass.Load\n 'Do some base stuff'\n End Sub\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 230432,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<pre><code> Partial Class OverheadClass\n Inherits System.Web.UI.Page\n\n Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) \n MyBase.OnLoad(e)\n End Sub\nEnd Class\n\n\n\nPartial Class _Default\n Inherits OverheadClass\n\n Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) \n MyBase.OnLoad(e)\n End Sub\nEnd Class\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12545/"
] |
I am trying to aid another programmer with a page called Default.aspx with a code-behind section, and unfortunately I am at a bit of a loss.
```
Partial Class _Default
Inherits OverheadClass
'A bunch of global variables here'
Private Sub page_load(ByVal sender As Object, ByVal e As System.Eventarts) Handles Me.Load
'Function goes here'
```
And in the OverheadClass we have
```
Public Sub Sub_OverheadClass_Load(ByVal sender As Object, ByVal e as System.EventArgs) Handles MyClass.Load
```
The desired effect is when the OverheadClass is inherited, we want its load to run before the load event on the page runs. There is probably a very simple answer to this that I am missing.
Edit: I forgot to note that we write in VB, and not C# as many of you are used to for ASP.
|
You should be able to override the OnLoad and call the base class's OnLoad first, then your class, for example:
C# Version
```
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Do some stuff here
}
```
VB Version
```
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
' Do some stuff here
End Sub
```
|
230,196 |
<p>I need write an update statement that used multiple tables to determine which rows to update, since in Oracle, multiple tables aren't allowed. The following query will return a "ORA-00971: Missing SET keyword" error</p>
<pre><code>UPDATE
TABLE1 a,
TABLE2 b
SET
a.COL1 = 'VALUE'
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
</code></pre>
<p>Looking up the UPDATE statement syntax on oracle, I found the following <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/update_statement.htm" rel="noreferrer">link</a>, which shows that you can use a subquery in place of a table name.</p>
<p>When I tried to write the query like this, I got a "ORA-01779: Cannot modify a column which maps to a non key-preserved table"</p>
<pre><code>UPDATE
(
SELECT
a.COL1
FROM
TABLE1 a,
TABLE2 b
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
) update_tbl
SET
update_tbl.COL1 = 'VALUE'
</code></pre>
<p>I did rewrite the query (show below) using an EXISTS statement instead and it works fine, but would still like to know how this is done.</p>
<pre><code>UPDATE
TABLE1 update_tbl
SET
update_tbl.COL1 = 'VALUE'
WHERE
EXISTS (
SELECT
1
FROM
TABLE1 a
TABLE2 b
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
AND update_tbl.PK = a.PK
)
</code></pre>
<p>Thanks!
-Nate</p>
|
[
{
"answer_id": 230213,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 0,
"selected": false,
"text": "<p>Each row in the result set of the query in your UPDATE clause must map back to one and only one row in the table you are trying to update, and in a way that Oracle can follow automatically. Since the query is really a view, one way to think about it is that Oracle needs to be able to join the view back to the target table, in order to know what row to update.</p>\n\n<p>This essentially means that you need to include the primary key of the destination table in that query. You might be able to use some other unique index field(s) too, but I can't guarantee the Oracle DBMS is smart enough to allow that.</p>\n"
},
{
"answer_id": 230251,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": true,
"text": "<p>Another option:</p>\n\n<pre><code>UPDATE TABLE1 a\nSET a.COL1 = 'VALUE'\nWHERE a.FK IN\n( SELECT b.PK FROM TABLE2 b\n WHERE b.COL2 IN ('SET OF VALUES')\n)\n</code></pre>\n\n<p>Your second example would work if (a) the view included the <strong>declared</strong> PK of TABLE1:</p>\n\n<pre><code>UPDATE\n (\n SELECT\n a.COL1, a.PKCOL\n FROM\n TABLE1 a,\n TABLE2 b\n WHERE\n a.FK = b.PK\n AND b.COL2 IN ('SET OF VALUES')\n ) update_tbl\nSET\n update_tbl.COL1 = 'VALUE'\n</code></pre>\n\n<p>... and (b) TABLE1.FK was a <strong>declared</strong> foreign key to TABLE2</p>\n\n<p>(By declared I mean that a constraint exists and is enabled).</p>\n"
},
{
"answer_id": 230776,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 2,
"selected": false,
"text": "<p>When you perform an update you can obviously only tell the system to update the value to a single new value -- telling it to update \"X\" to both \"Y\" and \"Z\" doesn't make sense. So, when you base an update on the result of an inline view Oracle performs a check that there are sufficient constraints in place to prevent a modified column being potentially updated twice.</p>\n\n<p>In your case I expect that TABLE2.PK is not actually a declared primary key. If you place a primary or unique constraint on that columnthen you'd be good to go.</p>\n\n<p>There is an undocumented hint to byass the update join cardinality check, used internally by Oracle, but I wouldn't advise using it.</p>\n\n<p>One workaround for this is to use a MERGE statement, which is not subject to the same test.</p>\n"
},
{
"answer_id": 230851,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>The syntax of your example is fine, but Oracle requires that the subquery include primary keys. That's a pretty significant limitation.</p>\n\n<p>On a related note, you can also use parentheses to use 2 or more fields in an IN statement, as in:</p>\n\n<pre><code>UPDATE\n TABLE1 update_tbl\nSET\n update_tbl.COL1 = 'VALUE'\nWHERE\n (update_tbl.PK1, update_tbl.pk2) in(\n select some_field1, some_field2\n from some_table st\n where st.some_fields = 'some conditions'\n );\n</code></pre>\n"
},
{
"answer_id": 233069,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 3,
"selected": false,
"text": "<p>I find that a nice, quick, consistent way to turn a SELECT statement into an UPDATE is to make the update based on the ROWID.</p>\n\n<pre><code>UPDATE\n TABLE1\nSET\n COL1 = 'VALUE'\nWHERE\n ROWID in\n (\n SELECT\n a.rowid\n FROM\n TABLE1 a,\n TABLE2 b\n WHERE\n a.FK = b.PK\n AND b.COL2 IN ('SET OF VALUES')\n )\n</code></pre>\n\n<p>So, your inner query is defining the rows to update.</p>\n"
},
{
"answer_id": 6147880,
"author": "Franck",
"author_id": 772454,
"author_profile": "https://Stackoverflow.com/users/772454",
"pm_score": 1,
"selected": false,
"text": "<p>I found what i needed here:\n<a href=\"http://infolab.stanford.edu/~ullman/fcdb/oracle/or-plsql.html\" rel=\"nofollow\">Useful SQL Commands</a>\n<br><br>\nI needed to update one table with the result of a join<br>\nI tried the above solutions without success :(<br></p>\n\n<p>Here is an extract of the page i pointed above<br>\nUsing cursors i was able to achieve the task successfully<br>\nI'm sure there's another solution but this one worked so...<br><br></p>\n\n<pre><code>DECLARE\n\n /* Output variables to hold the result of the query: */\n a T1.e%TYPE;\n b T2.f%TYPE;\n c T2.g%TYPE;\n\n /* Cursor declaration: */\n CURSOR T1Cursor IS\n SELECT T1.e, T2.f, T2.g\n FROM T1, T2\n WHERE T1.id = T2.id AND T1.e <> T2.f\n\n FOR UPDATE;\n\nBEGIN\n\n OPEN T1Cursor;\n\n LOOP\n\n /* Retrieve each row of the result of the above query\n into PL/SQL variables: */\n FETCH T1Cursor INTO a, b;\n\n /* If there are no more rows to fetch, exit the loop: */\n EXIT WHEN T1Cursor%NOTFOUND;\n\n /* Delete the current tuple: */\n DELETE FROM T1 WHERE CURRENT OF T1Cursor;\n\n /* Insert the reverse tuple: */\n INSERT INTO T1 VALUES(b, a);\n\n /* Here is my stuff using the variables to update my table */\n UPDATE T2\n SET T2.f = a\n WHERE T2.id = c;\n\n END LOOP;\n\n /* Free cursor used by the query. */\n CLOSE T1Cursor;\n\nEND;\n.\nrun;\n</code></pre>\n\n<p><br>Note: Don't forget to commit ;-)<br></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5129/"
] |
I need write an update statement that used multiple tables to determine which rows to update, since in Oracle, multiple tables aren't allowed. The following query will return a "ORA-00971: Missing SET keyword" error
```
UPDATE
TABLE1 a,
TABLE2 b
SET
a.COL1 = 'VALUE'
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
```
Looking up the UPDATE statement syntax on oracle, I found the following [link](http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/update_statement.htm), which shows that you can use a subquery in place of a table name.
When I tried to write the query like this, I got a "ORA-01779: Cannot modify a column which maps to a non key-preserved table"
```
UPDATE
(
SELECT
a.COL1
FROM
TABLE1 a,
TABLE2 b
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
) update_tbl
SET
update_tbl.COL1 = 'VALUE'
```
I did rewrite the query (show below) using an EXISTS statement instead and it works fine, but would still like to know how this is done.
```
UPDATE
TABLE1 update_tbl
SET
update_tbl.COL1 = 'VALUE'
WHERE
EXISTS (
SELECT
1
FROM
TABLE1 a
TABLE2 b
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
AND update_tbl.PK = a.PK
)
```
Thanks!
-Nate
|
Another option:
```
UPDATE TABLE1 a
SET a.COL1 = 'VALUE'
WHERE a.FK IN
( SELECT b.PK FROM TABLE2 b
WHERE b.COL2 IN ('SET OF VALUES')
)
```
Your second example would work if (a) the view included the **declared** PK of TABLE1:
```
UPDATE
(
SELECT
a.COL1, a.PKCOL
FROM
TABLE1 a,
TABLE2 b
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
) update_tbl
SET
update_tbl.COL1 = 'VALUE'
```
... and (b) TABLE1.FK was a **declared** foreign key to TABLE2
(By declared I mean that a constraint exists and is enabled).
|
230,205 |
<p>I have a page that is supposed to launch the Print Preview page onload.</p>
<p>I found this:</p>
<pre><code>var OLECMDID = 7;
/* OLECMDID values:
* 6 - print
* 7 - print preview
* 1 - open window
* 4 - Save As
*/
var PROMPT = 1; // 2 DONTPROMPTUSER
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(OLECMDID, PROMPT);
WebBrowser1.outerHTML = "";
</code></pre>
<p>But...</p>
<ol>
<li>it does not work in FireFox.</li>
<li>it's kind of ugly.</li>
</ol>
<p>Is there a better way for IE or a way that works for FireFox?</p>
|
[
{
"answer_id": 230231,
"author": "svandragt",
"author_id": 997,
"author_profile": "https://Stackoverflow.com/users/997",
"pm_score": 6,
"selected": true,
"text": "<p>You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.</p>\n\n<p>That's why your example uses Active X, which bypasses the JavaScript security issues.</p>\n\n<p>So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.</p>\n\n<p>Read <a href=\"http://www.alistapart.com/articles/goingtoprint/\" rel=\"noreferrer\">Alist Apart: Going to Print</a> for a good article on the subject of print stylesheets.</p>\n"
},
{
"answer_id": 230243,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>I think the best that's possible in cross-browser JavaScript is <code>window.print()</code>, which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.</p>\n<p>FYI, the <em>print dialog</em> is your computer's Print popup, what you get when you do Ctrl-p. The <em>print preview</em> is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...</p>\n"
},
{
"answer_id": 23774526,
"author": "Vikas Kottari",
"author_id": 2757125,
"author_profile": "https://Stackoverflow.com/users/2757125",
"pm_score": 3,
"selected": false,
"text": "<p>It can be done using javascript.\nSay your html/aspx code goes this way:</p>\n\n<pre><code><span>Main heading</span>\n<asp:Label ID=\"lbl1\" runat=\"server\" Text=\"Contents\"></asp:Label>\n<asp:Label Text=\"Contractor Name\" ID=\"lblCont\" runat=\"server\"></asp:Label>\n<div id=\"forPrintPreview\">\n <asp:Label Text=\"Company Name\" runat=\"server\"></asp:Label>\n <asp:GridView runat=\"server\">\n\n //GridView Content goes here\n\n </asp:GridView\n</div>\n\n<input type=\"button\" onclick=\"PrintPreview();\" value=\"Print Preview\" />\n</code></pre>\n\n<p>Here on click of \"Print Preview\" button we will open a window with data for print.\nObserve that 'forPrintPreview' is the id of a div.\nThe function for Print preview goes this way:</p>\n\n<pre><code>function PrintPreview() {\n var Contractor= $('span[id*=\"lblCont\"]').html();\n printWindow = window.open(\"\", \"\", \"location=1,status=1,scrollbars=1,width=650,height=600\");\n printWindow.document.write('<html><head>');\n printWindow.document.write('<style type=\"text/css\">@media print{.no-print, .no-print *{display: none !important;}</style>');\n printWindow.document.write('</head><body>');\n printWindow.document.write('<div style=\"width:100%;text-align:right\">');\n\n //Print and cancel button\n printWindow.document.write('<input type=\"button\" id=\"btnPrint\" value=\"Print\" class=\"no-print\" style=\"width:100px\" onclick=\"window.print()\" />');\n printWindow.document.write('<input type=\"button\" id=\"btnCancel\" value=\"Cancel\" class=\"no-print\" style=\"width:100px\" onclick=\"window.close()\" />');\n\n printWindow.document.write('</div>');\n\n //You can include any data this way.\n printWindow.document.write('<table><tr><td>Contractor name:'+ Contractor +'</td></tr>you can include any info here</table');\n\n printWindow.document.write(document.getElementById('forPrintPreview').innerHTML);\n //here 'forPrintPreview' is the id of the 'div' in current page(aspx).\n printWindow.document.write('</body></html>');\n printWindow.document.close();\n printWindow.focus();\n}\n</code></pre>\n\n<p>Observe that buttons 'print' and 'cancel' has the css class 'no-print', So these buttons will not appear in the print.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27482/"
] |
I have a page that is supposed to launch the Print Preview page onload.
I found this:
```
var OLECMDID = 7;
/* OLECMDID values:
* 6 - print
* 7 - print preview
* 1 - open window
* 4 - Save As
*/
var PROMPT = 1; // 2 DONTPROMPTUSER
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(OLECMDID, PROMPT);
WebBrowser1.outerHTML = "";
```
But...
1. it does not work in FireFox.
2. it's kind of ugly.
Is there a better way for IE or a way that works for FireFox?
|
You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.
That's why your example uses Active X, which bypasses the JavaScript security issues.
So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.
Read [Alist Apart: Going to Print](http://www.alistapart.com/articles/goingtoprint/) for a good article on the subject of print stylesheets.
|
230,241 |
<p>I have a table, call it TBL. It has two columns,call them A and B. Now in the query I require one column as A and other column should be a comma seprated list of all B's which are against A in TBL.
e.g. TBL is like this</p>
<p>1 Alpha</p>
<p>2 Beta</p>
<p>1 Gamma</p>
<p>1 Delta</p>
<p>Result of query should be </p>
<p>1 Alpha,Gamma,Delta</p>
<p>2 Beta</p>
<p>This type of thing is very easy to do with cursors in stored procedure. But I am not able to do it through MS Access, because apparently it does not support stored procedures.
Is there a way to run stored procedure in MS access? or is there a way through SQL to run this type of query</p>
|
[
{
"answer_id": 230278,
"author": "Totty",
"author_id": 30838,
"author_profile": "https://Stackoverflow.com/users/30838",
"pm_score": 2,
"selected": false,
"text": "<p>There is not a way that I know of to run stored procedures in an Access database. However, Access can execute stored procedures if it is being used against a SQL backend. If you can not split the UI to Access and data to SQL, then your best bet will probably be to code a VBA module to give you the output you need.</p>\n"
},
{
"answer_id": 230283,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you can use a Recordset object to loop through your query in VBA, concatenating field values based on whatever criteria you need.</p>\n\n<p>If you want to return the results as strings, you'll be fine. If you want to return them as a query, that will be more complicated. You might have to create a temporary table and store the results in there so you can return them as a table or query.</p>\n"
},
{
"answer_id": 230330,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 1,
"selected": false,
"text": "<p>No stored procedures, no temporary tables.</p>\n\n<p>If you needed to return the query as a recordset, you could use a disconnected recordset.</p>\n"
},
{
"answer_id": 230431,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you can create VBA functions and use them in your access queries. That might help you. </p>\n"
},
{
"answer_id": 230823,
"author": "pro3carp3",
"author_id": 7899,
"author_profile": "https://Stackoverflow.com/users/7899",
"pm_score": 2,
"selected": false,
"text": "<p>To accomplish your task you will need to use code. One solution, using more meaningful names, is as follows:</p>\n<p>Main table with two applicable columns:</p>\n<blockquote>\n<p>Table Name: Widgets</p>\n<p>Field 1: ID (Long)</p>\n<p>Field 2: Color (Text 32)</p>\n</blockquote>\n<p>Add table with two columns:</p>\n<blockquote>\n<p>Table Name: ColorListByWidget</p>\n<p>Field 1: ID (Long)</p>\n<p>Field 2: ColorList (Text 255)</p>\n</blockquote>\n<p>Add the following code to a module and call as needed to update the ColorListByWidget table:</p>\n<pre><code>Public Sub GenerateColorList()\n\nDim cn As New ADODB.Connection\nDim Widgets As New ADODB.Recordset\nDim ColorListByWidget As New ADODB.Recordset\nDim ColorList As String\n\nSet cn = CurrentProject.Connection\n\ncn.Execute "DELETE * FROM ColorListByWidget"\ncn.Execute "INSERT INTO ColorListByWidget (ID) SELECT ID FROM Widgets GROUP BY ID"\n\nWith ColorListByWidget\n .Open "ColorListByWidget", cn, adOpenForwardOnly, adLockOptimistic, adCmdTable\n If Not (.BOF And .EOF) Then\n .MoveFirst\n Do Until .EOF\n Widgets.Open "SELECT Color FROM Widgets WHERE ID = " & .Fields("ID"), cn\n If Not (.BOF And .EOF) Then\n Widgets.MoveFirst\n ColorList = ""\n Do Until Widgets.EOF\n ColorList = ColorList & Widgets.Fields("Color").Value & ", "\n Widgets.MoveNext\n Loop\n End If\n .Fields("ColorList") = Left$(ColorList, Len(ColorList) - 2)\n .MoveNext\n Widgets.Close\n Loop\n End If\nEnd With\n\n\nEnd Sub\n</code></pre>\n<p>The ColorListByWidget Table now contains your desired information. Be careful that the list (colors in this example) does not exceed 255 characters.</p>\n"
},
{
"answer_id": 231570,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 5,
"selected": true,
"text": "<p>You can concatenate the records with a User Defined Function (UDF).</p>\n\n<p>The code below can be pasted 'as is' into a standard module. The SQL for you example would be:</p>\n\n<pre><code>SELECT tbl.A, Concatenate(\"SELECT B FROM tbl\n WHERE A = \" & [A]) AS ConcA\nFROM tbl\nGROUP BY tbl.A\n</code></pre>\n\n<p>This code is by DHookom, Access MVP, and is taken from <a href=\"http://www.tek-tips.com/faqs.cfm?fid=4233\" rel=\"noreferrer\">http://www.tek-tips.com/faqs.cfm?fid=4233</a></p>\n\n<pre><code>Function Concatenate(pstrSQL As String, _\n Optional pstrDelim As String = \", \") _\n As String\n 'example\n 'tblFamily with FamID as numeric primary key\n 'tblFamMem with FamID, FirstName, DOB,...\n 'return a comma separated list of FirstNames\n 'for a FamID\n ' John, Mary, Susan\n 'in a Query\n '(This SQL statement assumes FamID is numeric)\n '===================================\n 'SELECT FamID,\n 'Concatenate(\"SELECT FirstName FROM tblFamMem\n ' WHERE FamID =\" & [FamID]) as FirstNames\n 'FROM tblFamily\n '===================================\n '\n 'If the FamID is a string then the SQL would be\n '===================================\n 'SELECT FamID,\n 'Concatenate(\"SELECT FirstName FROM tblFamMem\n ' WHERE FamID =\"\"\" & [FamID] & \"\"\"\") as FirstNames\n 'FROM tblFamily\n '===================================\n\n '======For DAO uncomment next 4 lines=======\n '====== comment out ADO below =======\n 'Dim db As DAO.Database\n 'Dim rs As DAO.Recordset\n 'Set db = CurrentDb\n 'Set rs = db.OpenRecordset(pstrSQL)\n\n '======For ADO uncomment next two lines=====\n '====== comment out DAO above ======\n Dim rs As New ADODB.Recordset\n rs.Open pstrSQL, CurrentProject.Connection, _\n adOpenKeyset, adLockOptimistic\n Dim strConcat As String 'build return string\n With rs\n If Not .EOF Then\n .MoveFirst\n Do While Not .EOF\n strConcat = strConcat & _\n .Fields(0) & pstrDelim\n .MoveNext\n Loop\n End If\n .Close\n End With\n Set rs = Nothing\n '====== uncomment next line for DAO ========\n 'Set db = Nothing\n If Len(strConcat) > 0 Then\n strConcat = Left(strConcat, _\n Len(strConcat) - Len(pstrDelim))\n End If\n Concatenate = strConcat\nEnd Function \n</code></pre>\n"
},
{
"answer_id": 231596,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can use GetString in VBA which will return the recordset separated by any value you like (e.g. comma, dash, table cells etc.) although I have to admit I've only used it in VBScript, not Visual Basic. <a href=\"http://www.w3schools.com/ADO/met_rs_getstring.asp\" rel=\"nofollow noreferrer\">W3Schools has a good tutorial which will hopefully lend itself to your needs</a>.</p>\n"
},
{
"answer_id": 231811,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "<p>You can write your stored procedure as text and send it against the database with:</p>\n\n<pre><code>Dim sp as string\nsp = \"your stored procedure here\" (you can load it from a text file or a memo field?)\n\nAccess.CurrentProject.AccessConnection.Execute sp\n</code></pre>\n\n<p>This supposes you are using ADODB objects (ActiveX data Objects Library is coorectly referenced in your app).</p>\n\n<p>I am sure there is something similar with DAO ...</p>\n"
},
{
"answer_id": 232346,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps instead of asking if Jet has stored procedures, you should explain what you want to accomplish and then we can explain how to do it with Jet (it's not clear if you're using Access for your application, or just using a Jet MDB as your data store).</p>\n"
},
{
"answer_id": 232792,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 0,
"selected": false,
"text": "<p>@Remou on DHookom's Concatenate function: neither the SQL standard nor the Jet has a <code>CONCATENATE()</code> set function. Simply put, this is because it is a violation of 1NF. I'd prefer to do this on the application side rather than try to force SQL to do something it wasn't designed to do. Perhaps ACE's (Access2007) multi-valued types is a better fit: still NFNF but at least there is engine-level support. Remember, the question relates to a <em>stored</em> object: how would a user query a non-scalar column using SQL...?</p>\n\n<p>@David W. Fenton on whether Jet has stored procedures: didn't you and I discuss this in the newsgroups a couple of years ago. Since version 4.0, Jet/ACE has supported the \nfollowing syntax in ANSI-92 Query Mode:</p>\n\n<pre><code>CREATE PROCEDURE procedure (param1 datatype[, param2 datatype][, ...]) AS sqlstatement;\n\nEXECUTE procedure [param1[, param2[, ...]];\n</code></pre>\n\n<p>So Jet is creating and executing something it knows (in one mode at least) as a 'procedure' that is 'stored' in the MDB file. However, Jet/ACE SQL is pure and simple: it has no control-of-flow syntax and a <code>PROCEDURE</code> can only contain one SQL statement, so any <em>procedural</em> code is out of the question. Therefore, the answer to whether Jet has stored procedures is subjective.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613/"
] |
I have a table, call it TBL. It has two columns,call them A and B. Now in the query I require one column as A and other column should be a comma seprated list of all B's which are against A in TBL.
e.g. TBL is like this
1 Alpha
2 Beta
1 Gamma
1 Delta
Result of query should be
1 Alpha,Gamma,Delta
2 Beta
This type of thing is very easy to do with cursors in stored procedure. But I am not able to do it through MS Access, because apparently it does not support stored procedures.
Is there a way to run stored procedure in MS access? or is there a way through SQL to run this type of query
|
You can concatenate the records with a User Defined Function (UDF).
The code below can be pasted 'as is' into a standard module. The SQL for you example would be:
```
SELECT tbl.A, Concatenate("SELECT B FROM tbl
WHERE A = " & [A]) AS ConcA
FROM tbl
GROUP BY tbl.A
```
This code is by DHookom, Access MVP, and is taken from <http://www.tek-tips.com/faqs.cfm?fid=4233>
```
Function Concatenate(pstrSQL As String, _
Optional pstrDelim As String = ", ") _
As String
'example
'tblFamily with FamID as numeric primary key
'tblFamMem with FamID, FirstName, DOB,...
'return a comma separated list of FirstNames
'for a FamID
' John, Mary, Susan
'in a Query
'(This SQL statement assumes FamID is numeric)
'===================================
'SELECT FamID,
'Concatenate("SELECT FirstName FROM tblFamMem
' WHERE FamID =" & [FamID]) as FirstNames
'FROM tblFamily
'===================================
'
'If the FamID is a string then the SQL would be
'===================================
'SELECT FamID,
'Concatenate("SELECT FirstName FROM tblFamMem
' WHERE FamID =""" & [FamID] & """") as FirstNames
'FROM tblFamily
'===================================
'======For DAO uncomment next 4 lines=======
'====== comment out ADO below =======
'Dim db As DAO.Database
'Dim rs As DAO.Recordset
'Set db = CurrentDb
'Set rs = db.OpenRecordset(pstrSQL)
'======For ADO uncomment next two lines=====
'====== comment out DAO above ======
Dim rs As New ADODB.Recordset
rs.Open pstrSQL, CurrentProject.Connection, _
adOpenKeyset, adLockOptimistic
Dim strConcat As String 'build return string
With rs
If Not .EOF Then
.MoveFirst
Do While Not .EOF
strConcat = strConcat & _
.Fields(0) & pstrDelim
.MoveNext
Loop
End If
.Close
End With
Set rs = Nothing
'====== uncomment next line for DAO ========
'Set db = Nothing
If Len(strConcat) > 0 Then
strConcat = Left(strConcat, _
Len(strConcat) - Len(pstrDelim))
End If
Concatenate = strConcat
End Function
```
|
230,245 |
<p>Should the "visibility" for the <code>__destruct()</code> function be public or something else? I'm trying to write a standards doc for my group and this question came up.</p>
|
[
{
"answer_id": 230258,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 3,
"selected": false,
"text": "<p>I think it would need to be public in the case where a subclass needs to explicitly call the <strong>__destruct</strong> method of the parent class.</p>\n\n<p>Something like this would throw an error:</p>\n\n<pre><code><?php\nclass MyParent\n{\n private function __destruct()\n {\n echo 'Parent::__destruct';\n }\n}\n\nclass MyChild extends MyParent\n{\n function __destruct()\n {\n echo 'Child::__destruct';\n parent::__destruct();\n }\n}\n\n$myChild = new MyChild();\n?>\n</code></pre>\n"
},
{
"answer_id": 230358,
"author": "Dan Soap",
"author_id": 25253,
"author_profile": "https://Stackoverflow.com/users/25253",
"pm_score": 6,
"selected": true,
"text": "<p>In Addition to Mark Biek's answer:</p>\n\n<p>The __destruct() function must be declared public. Otherwise, the function will not be executed on script shutdown:</p>\n\n<pre><code>Warning: Call to protected MyChild1::__destruct() from context '' during shutdown ignored in Unknown on line 0\nWarning: Call to private MyChild2::__destruct() from context '' during shutdown ignored in Unknown on line 0\n</code></pre>\n\n<p>This may not be harmful, but rather unclean.</p>\n\n<p>But the most important thing about this: If the destructor is declared private or protected, the runtime will throw a fatal error in the moment the garbage collector tries to free objects:</p>\n\n<pre><code><?php\nclass MyParent\n{\n private function __destruct()\n {\n echo 'Parent::__destruct';\n }\n}\n\nclass MyChild extends MyParent\n{\n private function __destruct()\n {\n echo 'Child::__destruct';\n parent::__destruct();\n }\n}\n\n$myChild = new MyChild();\n$myChild = null;\n$myChild = new MyChild();\n\n?>\n</code></pre>\n\n<p>outputs</p>\n\n<pre><code>Fatal error: Call to private MyChild::__destruct() from context '' in D:\\www\\scratchbook\\destruct.php on line 20\n</code></pre>\n\n<p>(Thanks to Mark Biek for the excellent example!)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25143/"
] |
Should the "visibility" for the `__destruct()` function be public or something else? I'm trying to write a standards doc for my group and this question came up.
|
In Addition to Mark Biek's answer:
The \_\_destruct() function must be declared public. Otherwise, the function will not be executed on script shutdown:
```
Warning: Call to protected MyChild1::__destruct() from context '' during shutdown ignored in Unknown on line 0
Warning: Call to private MyChild2::__destruct() from context '' during shutdown ignored in Unknown on line 0
```
This may not be harmful, but rather unclean.
But the most important thing about this: If the destructor is declared private or protected, the runtime will throw a fatal error in the moment the garbage collector tries to free objects:
```
<?php
class MyParent
{
private function __destruct()
{
echo 'Parent::__destruct';
}
}
class MyChild extends MyParent
{
private function __destruct()
{
echo 'Child::__destruct';
parent::__destruct();
}
}
$myChild = new MyChild();
$myChild = null;
$myChild = new MyChild();
?>
```
outputs
```
Fatal error: Call to private MyChild::__destruct() from context '' in D:\www\scratchbook\destruct.php on line 20
```
(Thanks to Mark Biek for the excellent example!)
|
230,248 |
<p>Oracle Forms10g provides a tool to convert the Oracle Forms modules, from the binary format (.FMB) that Oracle Forms Builder works with, to text format (.FMT).</p>
<p>For example, if you create a module called <em>mymodule.fmb</em> with Oracle Forms Builder, and then invoke</p>
<pre><code>frmcmp module=mymodule.fmb script=yes batch=yes logon=no
</code></pre>
<p>from the command line, the Oracle Forms Convert utility will create a file named <em>mymodule.fmt</em> from the file <em>mymodule.fmb</em>. This text file is supposed to be "readable" by humans, except for the PL/SQL code of triggers and program units, which is codified.</p>
<p>For example, this is a snippet of a .FMT file with a chunk of codified PL/SQL code</p>
<pre><code>DEFINE F50P
BEGIN
PP = 10
PI = 3
PN = 464
PL = 1138
PV = (BLONG)
<<"
00000049 00800000 00440000 00000000 00000031 0000000d 00000002 a0011519
00002420 0000045e 001f0000 00165030 5f32335f 4f43545f 32303038 31365f33
375f3039 00000006 42454749 4e0a0000 0042676f 5f626c6f 636b2820 27504149
53455327 20293b0a 69662066 6f726d5f 73756363 65737320 7468656e 0a096578
65637574 655f7175 6572793b 0a656e64 2069663b 00000005 0a454e44 3b000000
1d574845 4e2d4e45 572d464f 524d2d49 4e535441 4e434520 28466f72 6d290000
</code></pre>
<p>Have you ever tried to decode this kind of files, to be able to extract the PL/SQL code of a form ?</p>
<p>It would be very useful to be able to search a string in the PL/SQL code of a lot of .FMT files, instead of using Oracle Forms Builder to manually open each of the corresponding .FMB files, and search the string in each one of them.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 231099,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 0,
"selected": false,
"text": "<p>According to <a href=\"http://www.orafaq.com/usenet/comp.databases.oracle.tools/2004/03/31/0352.htm\" rel=\"nofollow noreferrer\">this</a> page the author has a perl script to convert the hex back to ascii text (he says to send him an email and he will send it)</p>\n"
},
{
"answer_id": 231185,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "<p>The bytes are just hex values of the characters. for example: taking the 4th line and putting it into the following python code:</p>\n\n<pre><code>[chr(x) for x in [0x53,0x45,0x53,0x27 ,0x20,0x29,0x3b,0x0a ,0x69,0x66,0x20,0x66 ,0x6f,0x72,0x6d,0x5f ,0x73,0x75,0x63,0x63 ,0x65,0x73,0x73,0x20 ,0x74,0x68,0x65,0x6e ,0x0a,0x09,0x65,0x78]]\n</code></pre>\n\n<p>gives the following output:</p>\n\n<pre><code>['S', 'E', 'S', \"'\", ' ', ')', ';', '\\n', 'i', 'f', ' ', 'f', 'o', 'r', 'm', '_', 's', 'u', 'c', 'c', 'e', 's', 's', ' ', 't', 'h', 'e', 'n', '\\n', '\\t', 'e', 'x']\n</code></pre>\n\n<p>which is recognisable forms pl/sql. So it looks like it wouldn't be too much work to create a script that would take a directory of FMT files and produce corresponding files with text that could be searched.<br>\nHave fun!</p>\n"
},
{
"answer_id": 234722,
"author": "Thomas Jones-Low",
"author_id": 23030,
"author_profile": "https://Stackoverflow.com/users/23030",
"pm_score": 1,
"selected": false,
"text": "<p>The Oracle Forms 9i and later has an Programming API to allow you to do exactly what you describe. You will need to review your Forms documentation to do this, but it may be faster than trying to extract binary strings. </p>\n\n<p>If you are willing to pay for an existing tool, use the following: </p>\n\n<p><a href=\"http://www.orcl-toolbox.com/\" rel=\"nofollow noreferrer\">http://www.orcl-toolbox.com/</a></p>\n\n<p>Their formsAPI and FormsTools let you do extractions, diffs, changes and updates to your forms. </p>\n"
},
{
"answer_id": 235230,
"author": "Jim Hudson",
"author_id": 8051,
"author_profile": "https://Stackoverflow.com/users/8051",
"pm_score": 4,
"selected": true,
"text": "<p>Along with the API, note that if you're working at the start of this process you'll probably be better off generating the XML version than the FMT version. The FMT is an older format kept for backward compatibility, and tools like the recently announced Forms -> Oracle APEX converter will want the XML. It's also easier to read. </p>\n\n<p>In \"Forms 10g release 1\" (9.0.4) the XML converter is a separate command line program. forms2xml. I think that's still true for 10.1</p>\n\n<p>Plus, the XML is easier to read and interpret.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20037/"
] |
Oracle Forms10g provides a tool to convert the Oracle Forms modules, from the binary format (.FMB) that Oracle Forms Builder works with, to text format (.FMT).
For example, if you create a module called *mymodule.fmb* with Oracle Forms Builder, and then invoke
```
frmcmp module=mymodule.fmb script=yes batch=yes logon=no
```
from the command line, the Oracle Forms Convert utility will create a file named *mymodule.fmt* from the file *mymodule.fmb*. This text file is supposed to be "readable" by humans, except for the PL/SQL code of triggers and program units, which is codified.
For example, this is a snippet of a .FMT file with a chunk of codified PL/SQL code
```
DEFINE F50P
BEGIN
PP = 10
PI = 3
PN = 464
PL = 1138
PV = (BLONG)
<<"
00000049 00800000 00440000 00000000 00000031 0000000d 00000002 a0011519
00002420 0000045e 001f0000 00165030 5f32335f 4f43545f 32303038 31365f33
375f3039 00000006 42454749 4e0a0000 0042676f 5f626c6f 636b2820 27504149
53455327 20293b0a 69662066 6f726d5f 73756363 65737320 7468656e 0a096578
65637574 655f7175 6572793b 0a656e64 2069663b 00000005 0a454e44 3b000000
1d574845 4e2d4e45 572d464f 524d2d49 4e535441 4e434520 28466f72 6d290000
```
Have you ever tried to decode this kind of files, to be able to extract the PL/SQL code of a form ?
It would be very useful to be able to search a string in the PL/SQL code of a lot of .FMT files, instead of using Oracle Forms Builder to manually open each of the corresponding .FMB files, and search the string in each one of them.
Thanks!
|
Along with the API, note that if you're working at the start of this process you'll probably be better off generating the XML version than the FMT version. The FMT is an older format kept for backward compatibility, and tools like the recently announced Forms -> Oracle APEX converter will want the XML. It's also easier to read.
In "Forms 10g release 1" (9.0.4) the XML converter is a separate command line program. forms2xml. I think that's still true for 10.1
Plus, the XML is easier to read and interpret.
|
230,250 |
<p>Exception is:
'Country' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value</p>
<pre><code>UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();
</code></pre>
<p>The values held within dsCountry.tblDropDownValues are:</p>
<pre><code>Id AttrValue AttrName
aefa28e0-a118-11dd-ad8b-080c210c9a66 PLEASE SELECT Country
213a743e-ea0b-419c-bd44-03b1c35241b3 USA Country
eefa1387-8dc0-11d8-975f-13da67a41a5d CANADA Country
</code></pre>
|
[
{
"answer_id": 230284,
"author": "Jay S",
"author_id": 30440,
"author_profile": "https://Stackoverflow.com/users/30440",
"pm_score": 2,
"selected": false,
"text": "<p>Try binding the data on postback. It sounds like when the event handler is accessing the DropDownList, it hasn't been repopulated with the values you are initially binding to the DropDownList.</p>\n\n<p>Also, remember to bind early enough so that it is bound before the event handler starts its processing. OnInit or OnLoad should be good enough.</p>\n\n<p>Otherwise, might need some more details:</p>\n\n<ol>\n<li>When is the exception occurring? During the rendering, or on the postback in the event handler?</li>\n<li>Do you have a stack trace on the error that might point to the point in the code where the selected value is accessed?</li>\n<li>When are you binding the data?</li>\n</ol>\n"
},
{
"answer_id": 230306,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 0,
"selected": false,
"text": "<p>This could also be caused by having nulls in the source data you are binding to your drop down list.</p>\n"
},
{
"answer_id": 230354,
"author": "AndyG",
"author_id": 27678,
"author_profile": "https://Stackoverflow.com/users/27678",
"pm_score": 3,
"selected": true,
"text": "<p>Every time I got this error it was because the keys I was matching on to bind my data didn't match.</p>\n\n<p>The lines you showed may not be the problem. Look into when you are possibly loading a record from another table and binding their values into the dropdown list. </p>\n\n<p>For example, if you have a dropdown list on your page that contains all your country names with country Ids as Value-behinds These values are all stored in a table CountryTbl. You also have a grid on the page where a user can select which record from another table they want to edit. Let's say this record contains Information like Name, Phone #, and Country, and its all stored in another table UserTbl. When the form is attempting to bind its data from UserTbl, it is trying to set your Country DropDownList equal to a bound value from UserTbl.</p>\n\n<p>But what can happen, and has happened to me many times, is that you have bad data in your UserTbl like a Country that doesn't exist anymore, or another value in its Country field that just doesn't match any of your values in the Country Dropdown.</p>\n\n<p>Look into your database tables and see if you have any CountryIds in your \"UserTbl\" that don't match any of the ContryIds in your \"CountryTbl\".</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
Exception is:
'Country' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
```
UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();
```
The values held within dsCountry.tblDropDownValues are:
```
Id AttrValue AttrName
aefa28e0-a118-11dd-ad8b-080c210c9a66 PLEASE SELECT Country
213a743e-ea0b-419c-bd44-03b1c35241b3 USA Country
eefa1387-8dc0-11d8-975f-13da67a41a5d CANADA Country
```
|
Every time I got this error it was because the keys I was matching on to bind my data didn't match.
The lines you showed may not be the problem. Look into when you are possibly loading a record from another table and binding their values into the dropdown list.
For example, if you have a dropdown list on your page that contains all your country names with country Ids as Value-behinds These values are all stored in a table CountryTbl. You also have a grid on the page where a user can select which record from another table they want to edit. Let's say this record contains Information like Name, Phone #, and Country, and its all stored in another table UserTbl. When the form is attempting to bind its data from UserTbl, it is trying to set your Country DropDownList equal to a bound value from UserTbl.
But what can happen, and has happened to me many times, is that you have bad data in your UserTbl like a Country that doesn't exist anymore, or another value in its Country field that just doesn't match any of your values in the Country Dropdown.
Look into your database tables and see if you have any CountryIds in your "UserTbl" that don't match any of the ContryIds in your "CountryTbl".
|
230,262 |
<p>Is there a dialect of XML for defining the tables, indexes and relations of a relational database, and a "compiler" or stylesheet to transform that definition into SQL CREATE statements (DDL)?</p>
<p>EG, something that might look like:</p>
<pre><code><Table Name="orders">
<Column Name="order_id" Type="varchar" Size="20"/>
... etc ...
</Table>
</code></pre>
<p>I'd like to keep the configuration of a service and its dependencies all in one place, and XML is looking like the best choice because of its wide support and its ability to mix namespaces. With it, I could write an installation program that can install this service and create the database, its tables, indexes, relations, etc. without being tied to a specific SQL implementation.</p>
<p><strong>Edit:</strong> This has nothing to do with ORM. </p>
|
[
{
"answer_id": 230291,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like XML based migrations, never seen one though. </p>\n\n<p>If you're into OR/M you could take a look at (N)Hibernate's <a href=\"http://www.hibernate.org/hib_docs/reference/en/html/toolsetguide.html\" rel=\"nofollow noreferrer\">hbm2ddl</a> tool. It generates the appropriate create commands for the schema on various database dialects out of an XML definition.</p>\n"
},
{
"answer_id": 230311,
"author": "sanxiyn",
"author_id": 18382,
"author_profile": "https://Stackoverflow.com/users/18382",
"pm_score": 3,
"selected": true,
"text": "<p>Something like <a href=\"http://xml2ddl.berlios.de/\" rel=\"nofollow noreferrer\">xml2ddl</a>?</p>\n"
},
{
"answer_id": 232843,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 0,
"selected": false,
"text": "<p>I've written my own a couple of times for different projects. If you're good at XSLT, knowledgeable about DDL, and have a good development environment, it's surprisingly easy (like, 2 or 3 hours work) to hack together a schema for representing metadata and a transform that produces your database-creation script. </p>\n\n<p>This has all the usual advantages and disadvantages of doing it yourself: on the one hand, you control the feature set, but on the other hand, you're responsible for the feature set. In my projects, the feature set was small enough that it was easier to build it myself than it would have been to learn how to work with someone else's application framework. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
] |
Is there a dialect of XML for defining the tables, indexes and relations of a relational database, and a "compiler" or stylesheet to transform that definition into SQL CREATE statements (DDL)?
EG, something that might look like:
```
<Table Name="orders">
<Column Name="order_id" Type="varchar" Size="20"/>
... etc ...
</Table>
```
I'd like to keep the configuration of a service and its dependencies all in one place, and XML is looking like the best choice because of its wide support and its ability to mix namespaces. With it, I could write an installation program that can install this service and create the database, its tables, indexes, relations, etc. without being tied to a specific SQL implementation.
**Edit:** This has nothing to do with ORM.
|
Something like [xml2ddl](http://xml2ddl.berlios.de/)?
|
230,266 |
<p>Using Vim, I'm trying to pipe text selected in visual mode to a UNIX command and have the output appended to the end of the current file. For example, say we have a SQL command such as:</p>
<pre><code>SELECT * FROM mytable;
</code></pre>
<p>I want to do something like the following:</p>
<pre><code><ESC>
V " select text
:'<,'>!mysql -uuser -ppass mydb
</code></pre>
<p>But instead of having the output overwrite the currently selected text, I would like to have the output appended to the end of the file. You probably see where this is going. I'm working on using Vim as a simple SQL editor. That way, I don't have to leave Vim to edit, tweak, test SQL code.</p>
|
[
{
"answer_id": 230504,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 4,
"selected": true,
"text": "<p>How about copying the selected text to the end of the file, select the copy and run the command? If you do not want to repeat the same commands over and over again, you can record the sequence by using <code>q</code> or add a new command. I have tried the latter as follows:</p>\n\n<pre><code>:com -range C <line1>,<line2>yank | $ | put | .,$ !rev\n</code></pre>\n\n<p>With it you can select some lines and then type <code>:C</code>. This will first yank the selection, then go to the end of the file, paste the yanked text and run the command (<code>rev</code> in this case) over the new text.</p>\n"
},
{
"answer_id": 4934657,
"author": "Brad Cox",
"author_id": 100321,
"author_profile": "https://Stackoverflow.com/users/100321",
"pm_score": 0,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>:r | YourCommand\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>:r ! echo foo\n</code></pre>\n\n<p>adds <code>foo</code> to your buffer.</p>\n"
},
{
"answer_id": 12415821,
"author": "zah",
"author_id": 35511,
"author_profile": "https://Stackoverflow.com/users/35511",
"pm_score": 1,
"selected": false,
"text": "<p>If you prefer more programmatic approach, you can have</p>\n\n<pre><code>:call append(line(\"$\"), system(\"command\", GetSelectedText()))\n</code></pre>\n\n<p>where <code>GetSelectedText</code> is the reusable function:</p>\n\n<pre><code>func! GetSelectedText()\n normal gv\"xy\n let result = getreg(\"x\")\n normal gv\n return result\nendfunc\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8243/"
] |
Using Vim, I'm trying to pipe text selected in visual mode to a UNIX command and have the output appended to the end of the current file. For example, say we have a SQL command such as:
```
SELECT * FROM mytable;
```
I want to do something like the following:
```
<ESC>
V " select text
:'<,'>!mysql -uuser -ppass mydb
```
But instead of having the output overwrite the currently selected text, I would like to have the output appended to the end of the file. You probably see where this is going. I'm working on using Vim as a simple SQL editor. That way, I don't have to leave Vim to edit, tweak, test SQL code.
|
How about copying the selected text to the end of the file, select the copy and run the command? If you do not want to repeat the same commands over and over again, you can record the sequence by using `q` or add a new command. I have tried the latter as follows:
```
:com -range C <line1>,<line2>yank | $ | put | .,$ !rev
```
With it you can select some lines and then type `:C`. This will first yank the selection, then go to the end of the file, paste the yanked text and run the command (`rev` in this case) over the new text.
|
230,270 |
<p>I'm searching for a <strong>PHP syntax highlighting engine</strong> that can be customized (i.e. I can provide my <strong>own tokenizers</strong> for new languages) and that can handle several languages <em>simultaneously</em> (i.e. on the same output page). This engine has to work well together with <strong>CSS classes</strong>, i.e. it should format the output by inserting <code><span></code> elements that are adorned with <code>class</code> attributes. Bonus points for an extensible schema.</p>
<p>I do <em>not</em> search for a client-side syntax highlighting script (JavaScript).</p>
<p>So far, I'm stuck with <a href="http://qbnz.com/highlighter/" rel="noreferrer">GeSHi</a>. Unfortunately, GeSHi fails abysmally for several reasons. The main reason is that the different language files define completely different, inconsistent styles. I've worked hours trying to refactor the different language definitions down to a common denominator but since most definition files are in themselves quite bad, I'd finally like to switch.</p>
<p>Ideally, I'd like to have an API similar to <a href="http://coderay.rubychan.de/" rel="noreferrer">CodeRay</a>, <a href="http://pygments.org/" rel="noreferrer">Pygments</a> or the JavaScript <a href="http://code.google.com/p/syntaxhighlighter/" rel="noreferrer">dp.SyntaxHighlighter</a>.</p>
<h2>Clarification:</h2>
<p>I'm looking for a code highlighting software written <em>in</em> PHP, not <em>for</em> PHP (since I need to use it from inside PHP).</p>
|
[
{
"answer_id": 230404,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 3,
"selected": false,
"text": "<p>[I marked this answer as <em>Community Wiki</em> because you're specifically <em>not</em> looking for Javascript]</p>\n\n<p><strong><a href=\"http://softwaremaniacs.org/soft/highlight/\" rel=\"noreferrer\">http://softwaremaniacs.org/soft/highlight/</a></strong> is a PHP (<em>plus the following list of other languages supported</em>) syntax highlighting library:</p>\n\n<blockquote>\n <p><em>Python, Ruby, Perl, PHP, XML, HTML, CSS, Django, Javascript, VBScript, Delphi, Java, C++, C#, Lisp, RenderMan (RSL and RIB), Maya Embedded Language, SQL, SmallTalk, Axapta, 1C, Ini, Diff, DOS .bat, Bash</em></p>\n</blockquote>\n\n<p>It uses <em><span class=\"keyword\"></em> style markup.</p>\n\n<p>It has also been integrated in the <a href=\"http://dojotoolkit.org/\" rel=\"noreferrer\">dojo toolkit</a> (as a dojox project: <a href=\"http://trac.dojotoolkit.org/browser/dojox/trunk/lang/tests/test_highlight.html?rev=11623&format=txt\" rel=\"noreferrer\">dojox.lang.highlight</a>)</p>\n\n<p>Though not the most popular way to run a webserver, strictly speaking, Javascript is not only implemented on the client-side, but there are also <a href=\"http://en.wikipedia.org/wiki/Server-side_JavaScript\" rel=\"noreferrer\">Server-Side Javascript engine/platform combinations too</a>.</p>\n"
},
{
"answer_id": 230801,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 1,
"selected": false,
"text": "<p>Another option is to use the GPL <strong><a href=\"http://www.andre-simon.de/zip/download.html\" rel=\"nofollow noreferrer\">Highlight GUI</a></strong> program by Andre Simon which is available for most platforms. It converts PHP (and other languages) to HTML, RTF, XML, etc. which you can then cut and paste into the page you want. This way, the processing is only done once.</p>\n\n<p>The HTML is also CSS based, so you can change the style as you please.</p>\n\n<p>Personally, I use <strong><a href=\"http://www.dreamprojections.com/syntaxhighlighter\" rel=\"nofollow noreferrer\">dp.SyntaxHighlighter</a></strong>, but that uses client side Javascript, so it doesn't meet your needs. It does have a nice Windows Live plugin though which I find useful.</p>\n"
},
{
"answer_id": 233305,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": false,
"text": "<p>It might be worth looking at <a href=\"http://pear.php.net/package/Text_Highlighter/\" rel=\"nofollow noreferrer\">Pear_TextHighlighter</a> (<a href=\"http://pear.php.net/manual/en/package.text.text-highlighter.php\" rel=\"nofollow noreferrer\">documentation</a>)</p>\n\n<p>I think it won't by default output html exactly how you want it, but it does provide extensive capabilities for customisation (i.e. you can create different renderers/parsers)</p>\n"
},
{
"answer_id": 814716,
"author": "Mathias Bynens",
"author_id": 96656,
"author_profile": "https://Stackoverflow.com/users/96656",
"pm_score": 0,
"selected": false,
"text": "<p>Krijn Hoetmer's <a href=\"http://krijnhoetmer.nl/stuff/php/php-highlighter/\" rel=\"nofollow noreferrer\">PHP Highlighter</a> provides a completely customizable PHP class to highlight PHP syntax. The HTML it generates, validates under a strict doctype, and is completely stylable with CSS.</p>\n"
},
{
"answer_id": 819910,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": true,
"text": "<p>Since no existing tool satisfied my needs, I wrote my own. Lo and behold:</p>\n\n<h2><a href=\"https://github.com/klmr/hyperlight\" rel=\"noreferrer\">Hyperlight</a></h2>\n\n<p>Usage is extremely easy: just use</p>\n\n<pre><code> <?php hyperlight($code, 'php'); ?>\n</code></pre>\n\n<p>to highlight code. Writing new language definitions is relatively easy, too – using regular expressions and a powerful but simple state machine. By the way, I still <em>need</em> a lot of definitions so feel free to contribute.</p>\n"
},
{
"answer_id": 3490419,
"author": "Craig",
"author_id": 421333,
"author_profile": "https://Stackoverflow.com/users/421333",
"pm_score": 1,
"selected": false,
"text": "<p>A little late to chime in here, but I've been working on my own PHP syntax highlighting library. It is still in its early stages, but I am using it for all code samples on my blog.</p>\n\n<p>Just checked out Hyperlight. It looks pretty cool, but it is doing some pretty crazy stuff. Nested loops, processing line by line, etc. The core class is over 1000 lines of code. </p>\n\n<p>If you are interested in something simple and lightweight check out Nijikodo:\n<a href=\"http://www.craigiam.com/nijikodo\" rel=\"nofollow noreferrer\">http://www.craigiam.com/nijikodo</a></p>\n"
},
{
"answer_id": 6358880,
"author": "Gabor de Mooij",
"author_id": 237628,
"author_profile": "https://Stackoverflow.com/users/237628",
"pm_score": 1,
"selected": false,
"text": "<p>Why not use PHP's build-in syntax highlighter?</p>\n\n<p><a href=\"http://php.net/manual/en/function.highlight-string.php\" rel=\"nofollow\">http://php.net/manual/en/function.highlight-string.php</a></p>\n"
},
{
"answer_id": 14969976,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I had exactly the the same problem but as I was very short on time and needed really good code coverage I decided to write a PHP wrapper around <a href=\"http://pygments.org/\" rel=\"nofollow\">Pygments</a> library.</p>\n\n<p>It's called <a href=\"https://github.com/igorpan/PHPygmentizator\" rel=\"nofollow\">PHPygmentizator</a>. It's really simple to use. I wrote a very basic <a href=\"https://github.com/igorpan/PHPygmentizator/blob/master/doc/contents.md\" rel=\"nofollow\">manual</a>. As PHP is Web Development language primarily, I subordinated the structure to that fact and made it very easy to implement in almost any kind of website.</p>\n\n<p>It supports <a href=\"https://github.com/igorpan/PHPygmentizator/blob/master/doc/basic_usage.md\" rel=\"nofollow\">configuration files</a> and if that isn't enough and somebody needs to modify stuff in the process it also fires <a href=\"https://github.com/igorpan/PHPygmentizator/blob/master/doc/advanced_usage.md\" rel=\"nofollow\">events</a>.</p>\n\n<p>Demo of how it works can be found on basically any post of my blog which contains source code, <a href=\"http://www.pantovic.com/article/4/piflex-dependencyinjection\" rel=\"nofollow\">this one for example</a>.</p>\n\n<p>With default config you can just provide it a string in this format:</p>\n\n<pre><code>Any text here.\n\n[pygments=javascript]\nvar a = function(ar1, ar2) {\n return null;\n}\n[/pygments]\n\nAny text.\n</code></pre>\n\n<p>So it highlights code between tags (tags can be customized in configuration file) and leaves the rest untouched.</p>\n\n<p>Additionally I already made a Syntax recognition <em>library</em> (it uses algorithm which would probably be classified as <a href=\"http://en.wikipedia.org/wiki/Bayesian_probability\" rel=\"nofollow\">Bayesian probability</a>) which automatically recognizes which language code block is written in and can easily be hooked to one of <strong>PHPygmentizator</strong> events to provide automatic language recognition. I will probably make it public some time this week since I need to beautify the structure a bit and write some basic documentation. If you supply it with enough \"learning\" data it recognizes languages amazingly well, I tested even minified javascripts and languages which have similar keywords and structures and it has never made a mistake.</p>\n"
},
{
"answer_id": 22138962,
"author": "Taufik Nurrohman",
"author_id": 1163000,
"author_profile": "https://Stackoverflow.com/users/1163000",
"pm_score": 3,
"selected": false,
"text": "<p>I found this simple generic syntax highlighter written in PHP <a href=\"http://phoboslab.org/log/2007/08/generic-syntax-highlighting-with-regular-expressions\" rel=\"nofollow noreferrer\">here</a> and modified it a bit:</p>\n\n<pre><code><?php\n\n/**\n * Original => http://phoboslab.org/log/2007/08/generic-syntax-highlighting-with-regular-expressions\n * Usage => `echo SyntaxHighlight::process('source code here');`\n */\n\nclass SyntaxHighlight {\n public static function process($s) {\n $s = htmlspecialchars($s);\n\n // Workaround for escaped backslashes\n $s = str_replace('\\\\\\\\','\\\\\\\\<e>', $s); \n\n $regexp = array(\n\n // Comments/Strings\n '/(\n \\/\\*.*?\\*\\/|\n \\/\\/.*?\\n|\n \\#.[^a-fA-F0-9]+?\\n|\n \\&lt;\\!\\-\\-[\\s\\S]+\\-\\-\\&gt;|\n (?<!\\\\\\)&quot;.*?(?<!\\\\\\)&quot;|\n (?<!\\\\\\)\\'(.*?)(?<!\\\\\\)\\'\n )/isex' \n => 'self::replaceId($tokens,\\'$1\\')',\n\n // Punctuations\n '/([\\-\\!\\%\\^\\*\\(\\)\\+\\|\\~\\=\\`\\{\\}\\[\\]\\:\\\"\\'<>\\?\\,\\.\\/]+)/'\n => '<span class=\"P\">$1</span>',\n\n // Numbers (also look for Hex)\n '/(?<!\\w)(\n (0x|\\#)[\\da-f]+|\n \\d+|\n \\d+(px|em|cm|mm|rem|s|\\%)\n )(?!\\w)/ix'\n => '<span class=\"N\">$1</span>',\n\n // Make the bold assumption that an\n // all uppercase word has a special meaning\n '/(?<!\\w|>|\\#)(\n [A-Z_0-9]{2,}\n )(?!\\w)/x'\n => '<span class=\"D\">$1</span>',\n\n // Keywords\n '/(?<!\\w|\\$|\\%|\\@|>)(\n and|or|xor|for|do|while|foreach|as|return|die|exit|if|then|else|\n elseif|new|delete|try|throw|catch|finally|class|function|string|\n array|object|resource|var|bool|boolean|int|integer|float|double|\n real|string|array|global|const|static|public|private|protected|\n published|extends|switch|true|false|null|void|this|self|struct|\n char|signed|unsigned|short|long\n )(?!\\w|=\")/ix'\n => '<span class=\"K\">$1</span>',\n\n // PHP/Perl-Style Vars: $var, %var, @var\n '/(?<!\\w)(\n (\\$|\\%|\\@)(\\-&gt;|\\w)+\n )(?!\\w)/ix'\n => '<span class=\"V\">$1</span>'\n\n );\n\n $tokens = array(); // This array will be filled from the regexp-callback\n\n $s = preg_replace(array_keys($regexp), array_values($regexp), $s);\n\n // Paste the comments and strings back in again\n $s = str_replace(array_keys($tokens), array_values($tokens), $s);\n\n // Delete the \"Escaped Backslash Workaround Token\" (TM)\n // and replace tabs with four spaces.\n $s = str_replace(array('<e>', \"\\t\"), array('', ' '), $s);\n\n return '<pre><code>' . $s . '</code></pre>';\n }\n\n // Regexp-Callback to replace every comment or string with a uniqid and save\n // the matched text in an array\n // This way, strings and comments will be stripped out and wont be processed\n // by the other expressions searching for keywords etc.\n private static function replaceId(&$a, $match) {\n $id = \"##r\" . uniqid() . \"##\";\n\n // String or Comment?\n if(substr($match, 0, 2) == '//' || substr($match, 0, 2) == '/*' || substr($match, 0, 2) == '##' || substr($match, 0, 7) == '&lt;!--') {\n $a[$id] = '<span class=\"C\">' . $match . '</span>';\n } else {\n $a[$id] = '<span class=\"S\">' . $match . '</span>';\n }\n return $id;\n }\n}\n\n?>\n</code></pre>\n\n<p><strong>Demo:</strong> <a href=\"http://phpfiddle.org/lite/code/1sf-htn\" rel=\"nofollow noreferrer\">http://phpfiddle.org/lite/code/1sf-htn</a></p>\n\n<hr>\n\n<h3>Update</h3>\n\n<p>I just created a PHP port of my own JavaScript generic syntax highlighter here → <a href=\"https://github.com/taufik-nurrohman/generic-syntax-highlighter/blob/master/generic-syntax-highlighter.php\" rel=\"nofollow noreferrer\">https://github.com/taufik-nurrohman/generic-syntax-highlighter/blob/master/generic-syntax-highlighter.php</a></p>\n\n<p>How to use:</p>\n\n<pre><code><?php require 'generic-syntax-highlighter.php'; ?>\n<pre><code><?php echo SH('&lt;div class=\"foo\"&gt;&lt;/div&gt;'); ?></code></pre>\n</code></pre>\n"
},
{
"answer_id": 40471437,
"author": "Ghostff",
"author_id": 4036303,
"author_profile": "https://Stackoverflow.com/users/4036303",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://github.com/Ghostff/php_prettify\" rel=\"nofollow noreferrer\">PHP Prettify</a> Works fine so far, And has more customization than <a href=\"http://php.net/manual/en/function.highlight-string.php\" rel=\"nofollow noreferrer\">highlight_string </a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968/"
] |
I'm searching for a **PHP syntax highlighting engine** that can be customized (i.e. I can provide my **own tokenizers** for new languages) and that can handle several languages *simultaneously* (i.e. on the same output page). This engine has to work well together with **CSS classes**, i.e. it should format the output by inserting `<span>` elements that are adorned with `class` attributes. Bonus points for an extensible schema.
I do *not* search for a client-side syntax highlighting script (JavaScript).
So far, I'm stuck with [GeSHi](http://qbnz.com/highlighter/). Unfortunately, GeSHi fails abysmally for several reasons. The main reason is that the different language files define completely different, inconsistent styles. I've worked hours trying to refactor the different language definitions down to a common denominator but since most definition files are in themselves quite bad, I'd finally like to switch.
Ideally, I'd like to have an API similar to [CodeRay](http://coderay.rubychan.de/), [Pygments](http://pygments.org/) or the JavaScript [dp.SyntaxHighlighter](http://code.google.com/p/syntaxhighlighter/).
Clarification:
--------------
I'm looking for a code highlighting software written *in* PHP, not *for* PHP (since I need to use it from inside PHP).
|
Since no existing tool satisfied my needs, I wrote my own. Lo and behold:
[Hyperlight](https://github.com/klmr/hyperlight)
------------------------------------------------
Usage is extremely easy: just use
```
<?php hyperlight($code, 'php'); ?>
```
to highlight code. Writing new language definitions is relatively easy, too – using regular expressions and a powerful but simple state machine. By the way, I still *need* a lot of definitions so feel free to contribute.
|
230,335 |
<p>I started a Rails project recently and decided to use RESTful controllers. I created controllers for my key entities (such as Country) and added <code>index</code>, <code>new</code>, <code>edit</code>, <code>create</code>, <code>show</code>, <code>update</code> and <code>delete</code>. I added my <code>map.resources :country</code> to my routes file and life was good.</p>
<p>After development progressed a little, I started to encounter problems. I sometimes needed extra actions in my controller. First there was the <code>search</code> action that returned the options for my fancy autocompleting search box. Then came the need to display the countries in two different ways in different places in the application (the data displayed was different too, so it wasn't just two views) - I added the <code>index_full</code> action. Then I wanted to show a country by name in the URL, not by id so I added the <code>show_by_name</code> action.</p>
<p>What do you do when you need actions beyond the standard <code>index</code>, <code>new</code>, <code>edit</code>, <code>create</code>, <code>show</code>, <code>update</code>, <code>delete</code> in a RESTful controller in Rails? Do I need to add (and maintain) manual routes in the routes.rb file (which is a pain), do they go in a different controller, do I become unRESTful or am I missing something fundamental?</p>
<p>I guess I am asking, do I need to work harder and add actions into my routes.rb file for the privilege of being RESTful? If I wasn't using <code>map.resources</code> to add the REST goodies, the standard <code>:controller/:action, :controller/:action/:id</code> routes would handle pretty much everything automatically.</p>
|
[
{
"answer_id": 230523,
"author": "Codebeef",
"author_id": 12037,
"author_profile": "https://Stackoverflow.com/users/12037",
"pm_score": 4,
"selected": true,
"text": "<p>If I go beyond the standard CRUD actions with my models, I normally just add the methods as required. Searching is something I add to many controllers, but not every one, so I add it and maintain the routes normally:</p>\n\n<pre><code>map.resources :events, :collection => { :search => :get }\n</code></pre>\n\n<p>Moving these actions to an entirely separate controller might keep some of your controllers RESTful, but I find that keeping them in context is far more useful.</p>\n"
},
{
"answer_id": 230536,
"author": "Godeke",
"author_id": 28006,
"author_profile": "https://Stackoverflow.com/users/28006",
"pm_score": 3,
"selected": false,
"text": "<p>REST does not specify that you can't have additional views. No real world application is going to be able use only the supplied actions; this is why you can add your own actions.</p>\n\n<p>REST is about being able to make stateless calls to the server. Your search action is stateless each time as the data so far is supplied back, correct? Your alternate display action is also stateless, just a different view. </p>\n\n<p>As to if they should be manual routes or a new controller, that depends on how distinct the activity is. Your alternate view, if it provides a full set of CRUD (create, read, update, delete) operations would do well to be in a new controller. If you only have an alternate <em>view</em> to the data, I would just add an alternate view action.</p>\n\n<p>In other words, it doesn't sound like your application is failing to be RESTful, it is more an issue of realizing that the automatically generated feature set is a starting point, not a conclusion.</p>\n"
},
{
"answer_id": 230695,
"author": "Dave Nolan",
"author_id": 9474,
"author_profile": "https://Stackoverflow.com/users/9474",
"pm_score": 4,
"selected": false,
"text": "<p>I would treat <code>search</code> as a special case of <code>index</code>. Both actions return a collection of resources. The request parameters should specify things like page, limit, sort order, and search query.</p>\n\n<p>For example:</p>\n\n<pre><code>/resources/index # normal index\n/resources/index?query=foo # search for 'foo'\n</code></pre>\n\n<p>And in resources_controller:</p>\n\n<pre><code>before_filter :do_some_preprocessing_on_parameters\n\ndef index\n @resources = Resource.find_by_param(@preprocessed_params)\nend\n</code></pre>\n\n<p>As for <code>index_full</code> and <code>search_by_name</code>, you might look at splitting your current controller into two. There's a smell about what you've described.</p>\n\n<p>Having said that, you're absolutely right that there's no point in forcing your app to user restful routes when it doesn't deliver anything over <code>/:controller/:action/:id</code>. To make the decision, look how frequently you're using the restful resource route helpers in forms and links. If you're not using them, I wouldn't bother with it.</p>\n"
},
{
"answer_id": 235853,
"author": "theschmitzer",
"author_id": 2167252,
"author_profile": "https://Stackoverflow.com/users/2167252",
"pm_score": -1,
"selected": false,
"text": "<p>To remain RESTful in your design, you need to rethink what you call a resource.</p>\n\n<p>In your example a show action for a search controller, (search resource) is the direction to remain restful.</p>\n\n<p>In mine, I have a dashboard controller (show) and controllers for single fields of in-place ecditors (show and update)</p>\n"
},
{
"answer_id": 516738,
"author": "Jeremy",
"author_id": 62657,
"author_profile": "https://Stackoverflow.com/users/62657",
"pm_score": 0,
"selected": false,
"text": "<p>In my opinion they may have gone a bit off the rails here. What happened to DRY?</p>\n\n<p>I'm just getting back into Rails not having done much development with it since beta and I'm still waiting for the light-bulb to come on here. I'm still giving it a chance but if it hasn't happened for me by the end of my current project I'll probably just drop-back to the old standard routes and define the methods as I actually need them for the next one. </p>\n"
},
{
"answer_id": 961916,
"author": "Omar Qureshi",
"author_id": 84018,
"author_profile": "https://Stackoverflow.com/users/84018",
"pm_score": 0,
"selected": false,
"text": "<p>I won't go on to explain more about REST since I think that has been answered in this question, however I will talk a little bit about the default route.</p>\n\n<p>My main problem with the default route is that if you have multiple sites using the same Rails app it can look horrible.</p>\n\n<p>For example there may be controllers that you don't want people to be able to see on one app:</p>\n\n<pre><code>http://example1.somesite.com/example_2/foo/bar/1\n</code></pre>\n\n<p>compare this to</p>\n\n<pre><code>/:controller/:action/:id\n</code></pre>\n\n<p>This would go to the controller example_2/foo, action bar and id 1</p>\n\n<p>I consider this to be the main flaw of Rails' default route and this is something that RESTful routes (with subdomain extensions) or only named routes (<code>map.connect 'foo'</code> ... ) can fix.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16779/"
] |
I started a Rails project recently and decided to use RESTful controllers. I created controllers for my key entities (such as Country) and added `index`, `new`, `edit`, `create`, `show`, `update` and `delete`. I added my `map.resources :country` to my routes file and life was good.
After development progressed a little, I started to encounter problems. I sometimes needed extra actions in my controller. First there was the `search` action that returned the options for my fancy autocompleting search box. Then came the need to display the countries in two different ways in different places in the application (the data displayed was different too, so it wasn't just two views) - I added the `index_full` action. Then I wanted to show a country by name in the URL, not by id so I added the `show_by_name` action.
What do you do when you need actions beyond the standard `index`, `new`, `edit`, `create`, `show`, `update`, `delete` in a RESTful controller in Rails? Do I need to add (and maintain) manual routes in the routes.rb file (which is a pain), do they go in a different controller, do I become unRESTful or am I missing something fundamental?
I guess I am asking, do I need to work harder and add actions into my routes.rb file for the privilege of being RESTful? If I wasn't using `map.resources` to add the REST goodies, the standard `:controller/:action, :controller/:action/:id` routes would handle pretty much everything automatically.
|
If I go beyond the standard CRUD actions with my models, I normally just add the methods as required. Searching is something I add to many controllers, but not every one, so I add it and maintain the routes normally:
```
map.resources :events, :collection => { :search => :get }
```
Moving these actions to an entirely separate controller might keep some of your controllers RESTful, but I find that keeping them in context is far more useful.
|
230,337 |
<p>I'm making another app's window topmost to ensure that a click in my app brings the other's dialog into views. The problem I'm having is that I don't get focus back to my app after the call. If the other app has more windows one of them ends up with focus, and otherwise no window (looking at the taskbar only) gets focus. Where should I start investigating the issue? </p>
<p>My code for making the other app topmost is:</p>
<pre><code>Process p = Process.GetProcessById(trackedProcessID);
IntPtr h = p.MainWindowHandle;
uint TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS;
SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
</code></pre>
<p>with constants as</p>
<pre><code>public static readonly uint SWP_NOMOVE = 0x0002;
public static readonly uint SWP_NOSIZE = 0x0001;
public static readonly uint SWP_ASYNCWINDOWPOS = 0x4000;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
</code></pre>
|
[
{
"answer_id": 230349,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 3,
"selected": true,
"text": "<p>Related: <a href=\"https://stackoverflow.com/questions/48288/unexpected-behaviour-of-processmainwindowhandle\">Unexpected behaviour of Process.MainWindowHandle</a></p>\n\n<p>Basically MainWindowHandle gives you the current top-most window of the process despite what the documentation says.</p>\n\n<p>That explains why the main window of your other process doesn't necessarily get focus.</p>\n\n<p>Your other problem is because you are not returning focus to your app after giving it away.</p>\n\n<p>Actually, the correct term for what you are doing is establishing <a href=\"http://en.wikipedia.org/wiki/Z-order\" rel=\"nofollow noreferrer\">z-order</a>.</p>\n\n<p>Instead of trying to control z-order - which cannot be guaranteed - you might be better off sending messages to the other process.</p>\n"
},
{
"answer_id": 230630,
"author": "Joel Lucsy",
"author_id": 645,
"author_profile": "https://Stackoverflow.com/users/645",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried SWP_NOACTIVATE?</p>\n"
},
{
"answer_id": 241524,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": 0,
"selected": false,
"text": "<p>[Actual solution used]</p>\n\n<p>So far I'm going with sending the window handle of the calling window to the target app, and getting it to push it back on top when finished. It is a real pain as I will have ~50 windows to deal with, but it seems stable. The next approach, if this turns out to have problems, will be to call back to the calling app and ask it to push the window to the foreground, but I'd rather not as it introduces a possiblity that the user can do something to the calling app while the message is in transit (only a problem if there is a lot of messages comming in on the same transport protocol, which could well happen)</p>\n\n<p>Do not try to use the incoming window handle and set the parent of any window shown in the target app to that handle, it only makes the shown dialog to appear within the bounds of the calling app window, and cropped if necessary - useless</p>\n\n<p>Many thanks for the answers above to the question</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5472/"
] |
I'm making another app's window topmost to ensure that a click in my app brings the other's dialog into views. The problem I'm having is that I don't get focus back to my app after the call. If the other app has more windows one of them ends up with focus, and otherwise no window (looking at the taskbar only) gets focus. Where should I start investigating the issue?
My code for making the other app topmost is:
```
Process p = Process.GetProcessById(trackedProcessID);
IntPtr h = p.MainWindowHandle;
uint TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS;
SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
```
with constants as
```
public static readonly uint SWP_NOMOVE = 0x0002;
public static readonly uint SWP_NOSIZE = 0x0001;
public static readonly uint SWP_ASYNCWINDOWPOS = 0x4000;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
```
|
Related: [Unexpected behaviour of Process.MainWindowHandle](https://stackoverflow.com/questions/48288/unexpected-behaviour-of-processmainwindowhandle)
Basically MainWindowHandle gives you the current top-most window of the process despite what the documentation says.
That explains why the main window of your other process doesn't necessarily get focus.
Your other problem is because you are not returning focus to your app after giving it away.
Actually, the correct term for what you are doing is establishing [z-order](http://en.wikipedia.org/wiki/Z-order).
Instead of trying to control z-order - which cannot be guaranteed - you might be better off sending messages to the other process.
|
230,348 |
<p>I see Oracle procedures sometimes written with "AS", and sometimes with "IS" keyword. </p>
<pre><code>CREATE OR REPLACE Procedure TESTUSER.KILLINSTANCE (INSTANCEID integer) **AS**
...
</code></pre>
<p>vs.</p>
<pre><code>CREATE OR REPLACE Procedure TESTUSER.KILLINSTANCE (INSTANCEID integer) **IS**
...
</code></pre>
<p>Is there any difference between the two?</p>
<p><hr>
Edit: Apparently, there is no functional difference between the two, but some people follow a convention to use "AS" when the SP is part of a package and "IS" when it is not. Or the other way 'round. Meh.</p>
|
[
{
"answer_id": 230388,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 7,
"selected": true,
"text": "<p>None whatsover. They are synonyms supplied to make your code more readable:</p>\n\n<p>FUNCTION f IS ...</p>\n\n<p>CREATE VIEW v AS SELECT ...</p>\n"
},
{
"answer_id": 239256,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 6,
"selected": false,
"text": "<p>One minor difference...</p>\n\n<p>They are synonyms for packages and procedures, but not for cursors:</p>\n\n<p>This works...</p>\n\n<pre><code>cursor test_cursor\nis\nselect * from emp;\n</code></pre>\n\n<p>... but this doesn't:</p>\n\n<pre><code>cursor test_cursor\nas\nselect * from emp;\n</code></pre>\n"
},
{
"answer_id": 23082694,
"author": "StuartLC",
"author_id": 314291,
"author_profile": "https://Stackoverflow.com/users/314291",
"pm_score": 4,
"selected": false,
"text": "<p>Here's another difference (in 10g, at any rate)</p>\n\n<p>Given a loose object type:</p>\n\n<pre><code>CREATE TYPE someRecordType AS OBJECT\n(\n SomeCol VARCHAR2(12 BYTE)\n);\n</code></pre>\n\n<p>You can create a <code>loose</code> Table type of this object type with either <code>AS</code> or <code>IS</code></p>\n\n<pre><code>CREATE OR REPLACE TYPE someTableType\n IS {or AS} TABLE OF someRecordType;\n</code></pre>\n\n<p>However, if you create this same table type within a package, you must use <code>IS</code>:</p>\n\n<pre><code>CREATE OR REPLACE PACKAGE SomePackage IS\n TYPE packageTableType IS TABLE OF someRecordType;\nEND SomePackage;\n</code></pre>\n\n<p>Use of <code>AS</code> in the package yields the following error:</p>\n\n<blockquote>\n <p>Error(2,30): PLS-00103: Encountered the symbol \"TABLE\" when expecting one of the following: object opaque </p>\n</blockquote>\n"
},
{
"answer_id": 24282771,
"author": "Dileep Krishnamurthy",
"author_id": 3751989,
"author_profile": "https://Stackoverflow.com/users/3751989",
"pm_score": 5,
"selected": false,
"text": "<p>\"IS\" and \"AS\" act as a synonym while creating procedures and packages but not for a cursor, table or view.</p>\n"
},
{
"answer_id": 49369761,
"author": "Dániel Sándor",
"author_id": 5137315,
"author_profile": "https://Stackoverflow.com/users/5137315",
"pm_score": 1,
"selected": false,
"text": "<p>According to <a href=\"https://www.tutorialspoint.com/plsql/plsql_procedures.htm\" rel=\"nofollow noreferrer\">TutorialsPoint</a></p>\n\n<blockquote>\n <p>The AS keyword is used instead of the IS keyword for creating a\n standalone procedure.</p>\n</blockquote>\n\n<p>and considering previous answers,</p>\n\n<p>I guess</p>\n\n<p><code>AS</code> is for stand alone (outside of any block, subprogram, package) entities</p>\n\n<p>and</p>\n\n<p><code>IS</code> is for embedded (within a block, subprogram or package) entities.</p>\n\n<p>. </p>\n"
},
{
"answer_id": 50961567,
"author": "Pankaj Shivalkar",
"author_id": 7956590,
"author_profile": "https://Stackoverflow.com/users/7956590",
"pm_score": 1,
"selected": false,
"text": "<p>The <strong>AS</strong> keyword is used instead of the <strong>IS</strong> keyword for creating a <strong>standalone function</strong>.</p>\n\n<p>[ A <strong>standalone</strong> stored function is a function (<strong>a subprogram that returns a single value</strong>) that is stored in the database.\nNote: A standalone stored function that you create with the CREATE FUNCTION statement is <strong>different</strong> from a function that you declare and define in a PL/SQL block or package. ]</p>\n\n<p>For more explanation, <a href=\"https://docs.oracle.com/cd/B28359_01/appdev.111/b28370/function.htm#LNPLS01322\" rel=\"nofollow noreferrer\">read this</a>...</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227/"
] |
I see Oracle procedures sometimes written with "AS", and sometimes with "IS" keyword.
```
CREATE OR REPLACE Procedure TESTUSER.KILLINSTANCE (INSTANCEID integer) **AS**
...
```
vs.
```
CREATE OR REPLACE Procedure TESTUSER.KILLINSTANCE (INSTANCEID integer) **IS**
...
```
Is there any difference between the two?
---
Edit: Apparently, there is no functional difference between the two, but some people follow a convention to use "AS" when the SP is part of a package and "IS" when it is not. Or the other way 'round. Meh.
|
None whatsover. They are synonyms supplied to make your code more readable:
FUNCTION f IS ...
CREATE VIEW v AS SELECT ...
|
230,351 |
<p>When I am creating a new database table, what factors should I take into account for selecting the primary key's data type?</p>
|
[
{
"answer_id": 230362,
"author": "Ely",
"author_id": 30488,
"author_profile": "https://Stackoverflow.com/users/30488",
"pm_score": 3,
"selected": false,
"text": "<p>If using a numeric key, make sure the datatype is giong to be large enough to hold the number of rows you might expect the table to grow to.</p>\n\n<p>If using a guid, does the extra space needed to store the guid need to be considered? Will coding against guid PKs be a pain for developers or users of the application.</p>\n\n<p>If using composite keys, are you sure that the combined columns will always be unique?</p>\n"
},
{
"answer_id": 230366,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I usually always use an integer, but here's an interesting perspective.</p>\n\n<p><a href=\"https://blog.codinghorror.com/primary-keys-ids-versus-guids/\" rel=\"nofollow noreferrer\">https://blog.codinghorror.com/primary-keys-ids-versus-guids/</a></p>\n"
},
{
"answer_id": 230368,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 0,
"selected": false,
"text": "<p>I'm partial to using an generated integer key. If you expect the database to grow very large, you can go with bigint.</p>\n\n<p>Some people like to use guids. The pro there is that you can merge multiple instances of the database without altering any keys but the con is that performance can be affected.</p>\n"
},
{
"answer_id": 230372,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "<p>For a \"natural\" key, whatever datatype suits the column(s). Artifical (surrogate) keys are usually integers.</p>\n"
},
{
"answer_id": 230373,
"author": "Pradeep",
"author_id": 29693,
"author_profile": "https://Stackoverflow.com/users/29693",
"pm_score": 0,
"selected": false,
"text": "<p>It all depends.</p>\n\n<p>a) Are you fine having unique sequential numeric numbers as your primary key? If yes, then selecting UniqueIdentifier as your primary key will suffice.\nb) If your business demand is such that you need to have alpha numeric primary key, then you got to go for varchar or nvarchar.</p>\n\n<p>These are the two options I could think of.</p>\n"
},
{
"answer_id": 230375,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 3,
"selected": false,
"text": "<p>In most cases I use an identity int primary key, unless the scenario requires a lot of replication, in which case I may opt for a GUID.</p>\n\n<p>I (almost) never used meaningful keys.</p>\n"
},
{
"answer_id": 230378,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": -1,
"selected": false,
"text": "<p>Whenever possible, try to use a primary key that is a natural key. For instance, if I had a table where I logged one record every day, the logdate would be a good primary key. Otherwise, if there is no natural key, just use int. If you think you will use more than 2 billion rows, use a bigint. Some people like to use GUIDs, which works well, as they are unique, and you will never run out of space. However, they are needlessly long, and hard to type in if you are just doing adhoc queries.</p>\n"
},
{
"answer_id": 230380,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "<p>Do not use a floating point numeric type, since floating point numbers cannot be properly compared for equality.</p>\n"
},
{
"answer_id": 230381,
"author": "Matthias Meid",
"author_id": 17713,
"author_profile": "https://Stackoverflow.com/users/17713",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>Where do you generate it? Incrementing number's don't fit well for keys generated by the client.\n\n<ul>\n<li>Do you want a data-dependent or independent key (sometimes you could use an ID from business data, can't say if this is always useful or not)?</li>\n<li>How well can this type be indexed by your DB?</li>\n</ul></li>\n</ul>\n\n<p>I have used uniqueidentifiers (GUIDs) or incrementing integers so far.</p>\n\n<p>Cheers\nMatthias</p>\n"
},
{
"answer_id": 230386,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 0,
"selected": false,
"text": "<p>A great factor is how much data you're going to store. I work for a web analytics company, and we have LOADS of data. So a GUID primary key on our pageviews table would kill us, due to the size.</p>\n\n<p>A rule of thumb: For high performance, you should be able to store your entire index in memory. Guids could easily break this!</p>\n"
},
{
"answer_id": 230438,
"author": "Jan Gressmann",
"author_id": 6200,
"author_profile": "https://Stackoverflow.com/users/6200",
"pm_score": 3,
"selected": false,
"text": "<p>I don't really like what they teach in school, that is using a 'natural key' (for example ISBN on a bookdatabase) or even having a primary key made up off 2 or more fields. I would never do that. So here's my little advice:</p>\n\n<ul>\n<li><strong>Always have one dedicated column in every table for your primary key.</strong></li>\n<li><strong>They all should have the same colomn name across all tables, i.e. \"ID\" or \"GUID\"</strong></li>\n<li><strong>Use GUIDs when you can (if you don't need performance), otherwise incrementing INTs</strong></li>\n</ul>\n\n<p>EDIT:<br>\nOkay, I think I need to explain my choices a little bit.</p>\n\n<ul>\n<li><p>Having a dedicated column namend the same across all table for you primary key, just makes your SQL-Statements a lot of easier to construct and easier for someone else (who might not be familiar with your database layout) easier to understand. Especially when you're doing lots of JOINS and things like that. You won't need to look up what's the primary key for a specific table, you already know, because it's the same everywhere.</p></li>\n<li><p>GUIDs vs. INTs doesn't really matters that much most of the time. Unless you hit the performance cap of GUIDs or doing database merges, you won't have major issues with one or another. <strong>BUT</strong> there's a reason I prefer GUIDs. The global uniqueness of GUIDs might always come in handy some day. Maybe you don't see a need for it now, but things like, synchronizing parts of the database to a laptop / cell phone or even finding datarecords without needing to know which table they're in, are great examples of the advantages GUIDs can provide. An Integer only identifies a record within the context of one table, whereas a GUID identifies a record everywhere.</p></li>\n</ul>\n"
},
{
"answer_id": 230521,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 1,
"selected": false,
"text": "<p>Numbers that have meaning in the real world are usually a bad idea, because every so often the real world changes the rules about how those numbers are used, in particular to allow duplicates, and then you've got a real mess on your hands.</p>\n"
},
{
"answer_id": 231127,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 0,
"selected": false,
"text": "<p>Use natural keys when they can be trusted. Some sources of natural keys can't be trusted. Years ago, the Social Security Administration used to occasionally mess up an assign the same SSN to two different people. Theyv'e probably fixed that by now. </p>\n\n<p>You can probably trust VINs for vehicles, and ISBNs for books (but not for pamphlets, which may not have an ISBN).</p>\n\n<p>If you use natural keys, the natural key will determine the datatype. </p>\n\n<p>If you can't trust any natural keys, create a synthetic key. I prefer integers for this purpose. Leave enough room for reasonable expansion.</p>\n"
},
{
"answer_id": 231865,
"author": "Noah Yetter",
"author_id": 30080,
"author_profile": "https://Stackoverflow.com/users/30080",
"pm_score": 2,
"selected": false,
"text": "<p>Unless you have an ultra-convenient natural key available, always use a synthetic (a.k.a. surrogate) key of a numeric type. Even if you do have a natural key available, you might want to consider using a synthetic key anyway and placing an additional unique index on your natural key. Consider what happened to higher-ed databases that used social security numbers as PKs when federal law changed, the costs of changing over to synthetic keys were enormous.</p>\n\n<p>Also, I have to disagree with the practice of naming every primary key the same, e.g. \"id\". This makes queries harder to understand, not easier. Primary keys should be named after the table. For example employee.employee_id, affiliate.affiliate_id, user.user_id, and so on.</p>\n"
},
{
"answer_id": 231919,
"author": "Tom",
"author_id": 13219,
"author_profile": "https://Stackoverflow.com/users/13219",
"pm_score": 0,
"selected": false,
"text": "<p>I usually go with a GUID column primary key for all tables (rowguid in mssql). What could be natural keys I make unique constraints. A typical example would be a produkt identification number that the user have to make up and ensure that is unique. If I need a sequence, like in a invoice i build a table to keep a lastnumber and a stored procedure to ensure serialized access. Or a Sequence in Oracle :-) I hate the \"social security number\" sample for natural keys as that number will never be alway awailable in a registration process. Resulting in a need for a scheme to generate dummy numbers.</p>\n"
},
{
"answer_id": 232985,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 5,
"selected": true,
"text": "<p>Sorry to do that, but I found that the answers I gave to related questions (you can check <a href=\"https://stackoverflow.com/questions/159087/composite-primary-keys-versus-unique-object-id-field#164338\">this</a> and <a href=\"https://stackoverflow.com/questions/224576/will-sql-server-2005-penalize-me-for-using-an-nvarchar50-as-a-primary-key-inste#225407\">this</a>) could apply to this one. I reshaped them a little bit...</p>\n\n<p>You will find many posts dealing with this issue, and each choice you'll make has its pros and cons. Arguments for these usually refer to relational database theory and database performance.</p>\n\n<p>On this subject, my point is very simple: <strong><em>surrogate primary keys ALWAYS work</em></strong>, while <strong><em>Natural keys MIGHT NOT ALWAYS work one of these days</em></strong>, and this for multiple reasons: field too short, rules change, etc.</p>\n\n<p>To this point, you've guessed here that I am basically a member of the uniqueIdentifier/surrogate primary key team, and even if I appreciate and understand arguments such as the ones presented here, I am still looking for the case where \"natural\" key is better than surrogate ... </p>\n\n<p>In addition to this, one of the most important but always forgotten arguments in favor of this basic rule is related to <strong>code normalization and productivity</strong>:</p>\n\n<p>each time I create a table, <strong>shall I lose time</strong></p>\n\n<ol>\n<li>identifying its primary key and its physical characteristics (type, size)</li>\n<li>remembering these characteristics each time I want to refer to it in my code?</li>\n<li>explaining my PK choice to other developers in the team?</li>\n</ol>\n\n<p><strong>My answer is no</strong> to all of these questions:</p>\n\n<ol>\n<li>I have no time to lose trying to identify \"the best Natural Primary Key\" when the surrogate option gives me a bullet-proof solution.</li>\n<li>I do not want to remember that the Primary Key of my Table_whatever is a 10 characters long string when I write the code.</li>\n<li>I don't want to lose my time negotiating the Natural Key length: \"well if You need 10 why don't you take 12 <strong><em>to be on the safe side</em></strong>?\". This <strong><em>\"on the safe side\"</em></strong> argument really annoys me: If you want to stay on the safe side, it means that you are really not far from the unsafe side! Choose surrogate: it's bullet-proof!</li>\n</ol>\n\n<p>So I've been working for the last five years with a very basic rule: each table (let's call it 'myTable') has its first field called <code>'id_MyTable'</code> which is of uniqueIdentifier type. Even if this table supports a \"many-to-many\" relation, where a field combination offers a very acceptable Primary Key, I prefer to create this <code>'id_myManyToManyTable'</code> field being a uniqueIdentifier, just to stick to the rule, and because, finally, it does not hurt.</p>\n\n<p>The major advantage is that you don't have to care anymore about the use of Primary Key and/or Foreign Key within your code. Once you have the table name, you know the PK name and type. Once you know which links are implemented in your data model, you'll know the name of available foreign keys in the table.</p>\n\n<p>And if you still want to have your \"Natural Key\" somewhere in your table, I advise you to build it following a standard model such as </p>\n\n<pre><code>Tbl_whatever\n\n id_whatever, unique identifier, primary key\n code_whatever, whateverTypeYouWant(whateverLengthYouEstimateTheRightOne), indexed\n .....\n</code></pre>\n\n<p>Where id_ is the prefix for primary key, and code_ is used for \"natural\" indexed field. Some would argue that the code_ field should be set as unique. This is true, and it can be easily managed either through DDL or external code. Note that many \"natural\" keys are calculated (invoice numbers), so they are already generated through code</p>\n\n<p>I am not sure that my rule is the best one. But it is a very efficient one! If everyone was applying it, we would for example avoid time lost answering to this kind of question!</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5618/"
] |
When I am creating a new database table, what factors should I take into account for selecting the primary key's data type?
|
Sorry to do that, but I found that the answers I gave to related questions (you can check [this](https://stackoverflow.com/questions/159087/composite-primary-keys-versus-unique-object-id-field#164338) and [this](https://stackoverflow.com/questions/224576/will-sql-server-2005-penalize-me-for-using-an-nvarchar50-as-a-primary-key-inste#225407)) could apply to this one. I reshaped them a little bit...
You will find many posts dealing with this issue, and each choice you'll make has its pros and cons. Arguments for these usually refer to relational database theory and database performance.
On this subject, my point is very simple: ***surrogate primary keys ALWAYS work***, while ***Natural keys MIGHT NOT ALWAYS work one of these days***, and this for multiple reasons: field too short, rules change, etc.
To this point, you've guessed here that I am basically a member of the uniqueIdentifier/surrogate primary key team, and even if I appreciate and understand arguments such as the ones presented here, I am still looking for the case where "natural" key is better than surrogate ...
In addition to this, one of the most important but always forgotten arguments in favor of this basic rule is related to **code normalization and productivity**:
each time I create a table, **shall I lose time**
1. identifying its primary key and its physical characteristics (type, size)
2. remembering these characteristics each time I want to refer to it in my code?
3. explaining my PK choice to other developers in the team?
**My answer is no** to all of these questions:
1. I have no time to lose trying to identify "the best Natural Primary Key" when the surrogate option gives me a bullet-proof solution.
2. I do not want to remember that the Primary Key of my Table\_whatever is a 10 characters long string when I write the code.
3. I don't want to lose my time negotiating the Natural Key length: "well if You need 10 why don't you take 12 ***to be on the safe side***?". This ***"on the safe side"*** argument really annoys me: If you want to stay on the safe side, it means that you are really not far from the unsafe side! Choose surrogate: it's bullet-proof!
So I've been working for the last five years with a very basic rule: each table (let's call it 'myTable') has its first field called `'id_MyTable'` which is of uniqueIdentifier type. Even if this table supports a "many-to-many" relation, where a field combination offers a very acceptable Primary Key, I prefer to create this `'id_myManyToManyTable'` field being a uniqueIdentifier, just to stick to the rule, and because, finally, it does not hurt.
The major advantage is that you don't have to care anymore about the use of Primary Key and/or Foreign Key within your code. Once you have the table name, you know the PK name and type. Once you know which links are implemented in your data model, you'll know the name of available foreign keys in the table.
And if you still want to have your "Natural Key" somewhere in your table, I advise you to build it following a standard model such as
```
Tbl_whatever
id_whatever, unique identifier, primary key
code_whatever, whateverTypeYouWant(whateverLengthYouEstimateTheRightOne), indexed
.....
```
Where id\_ is the prefix for primary key, and code\_ is used for "natural" indexed field. Some would argue that the code\_ field should be set as unique. This is true, and it can be easily managed either through DDL or external code. Note that many "natural" keys are calculated (invoice numbers), so they are already generated through code
I am not sure that my rule is the best one. But it is a very efficient one! If everyone was applying it, we would for example avoid time lost answering to this kind of question!
|
230,364 |
<p>I'm trying to link an RPATH containing the special string $ORIGIN into an executable built using GCC with the Code::Blocks IDE. I've specified</p>
<pre><code>-Wl,-R$ORIGIN
</code></pre>
<p>in the linker options for the project, but the command line output to GCC is wrong (stripped for clarity):</p>
<pre><code>g++ -Wl,-R
</code></pre>
<p>What is the correct way to specify this argument for Code::Blocks?</p>
|
[
{
"answer_id": 230376,
"author": "kbluck",
"author_id": 13402,
"author_profile": "https://Stackoverflow.com/users/13402",
"pm_score": 6,
"selected": true,
"text": "<p>Whoever decided to make the token $ORIGIN is an evil bastard who deserves a special place in programmer hell. Since '$' is a special character for bash and other scripting languages like make, it screws everything up unless carefully escaped. Even worse, depending on which build environment you're using, the specifics of how to escape properly will likely change.</p>\n\n<p>In bash, you need to stick a backslash in front of the $:</p>\n\n<pre><code>-Wl,-R\\$ORIGIN\n</code></pre>\n\n<p>Code::Blocks apparently also treats the $ as special. Then, whatever subprocess controller Code::Blocks sends the command to treats the backslash as special. So, both the backslash and the $ need to be doubled up to get escaped properly. Therefore, in Code::Blocks linker settings, you need to specify:</p>\n\n<pre><code>-Wl,-R\\\\$$ORIGIN\n</code></pre>\n\n<p>...which outputs:</p>\n\n<pre><code>-Wl,-R\\\\$ORIGIN\n</code></pre>\n\n<p>...to the build log, but the shell actually gets sent:</p>\n\n<pre><code>-Wl,-R\\$ORIGIN\n</code></pre>\n\n<p>...which as mentioned above produces the desired result.</p>\n\n<p>What a pain.</p>\n"
},
{
"answer_id": 1500980,
"author": "user44538",
"author_id": 44538,
"author_profile": "https://Stackoverflow.com/users/44538",
"pm_score": 4,
"selected": false,
"text": "<p>In addition to kblucks answer that addresses the question for Code:Blocks....\nFor those like me who stumbled across this page looking for how to do this with Make.\nThe trick is to use an extra $ sign as an escape character and to enclose it with quotes:</p>\n\n<pre><code>-Wl,-R,'$$ORIGIN/../lib'\n</code></pre>\n\n<p>Full explanation can be had here:\n<a href=\"http://wayback.archive.org/web/20130915172134/http://itee.uq.edu.au/~daniel/using_origin/\" rel=\"nofollow noreferrer\">Using ORIGIN for a dynamic runtime library search path</a></p>\n"
},
{
"answer_id": 14385281,
"author": "greggo",
"author_id": 450000,
"author_profile": "https://Stackoverflow.com/users/450000",
"pm_score": 1,
"selected": false,
"text": "<p>If your executable is being built by a huge complex script environment not created by you, and you don't want to delve into with that, trying running with <code>setenv LD_RUN_PATH='$ORIGIN/../lib'</code>; if that doesn't work, a pragmatic approach is to create a wrapper for ld:</p>\n\n<pre><code>#!/bin/sh\nexec /usr/bin/ld -R '$ORIGIN/../lib' \"$@\"\n</code></pre>\n\n<p>... then do the build with that stub on the path. In practice it may be called to build .so files, or other executables, so you may need to make this a more complex script that decides whether to insert the RPATH. OR, run build without this, and with, and cherry pick.</p>\n\n<p>(here \"/usr/bin/ld\" is the ld that would normally have been run, which may be somewhere else. gcc may not pick up ld from the path, see gcc environment variables to override that. Mileage may vary. Single use only. Not warranted to be less awful than any other approach).</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13402/"
] |
I'm trying to link an RPATH containing the special string $ORIGIN into an executable built using GCC with the Code::Blocks IDE. I've specified
```
-Wl,-R$ORIGIN
```
in the linker options for the project, but the command line output to GCC is wrong (stripped for clarity):
```
g++ -Wl,-R
```
What is the correct way to specify this argument for Code::Blocks?
|
Whoever decided to make the token $ORIGIN is an evil bastard who deserves a special place in programmer hell. Since '$' is a special character for bash and other scripting languages like make, it screws everything up unless carefully escaped. Even worse, depending on which build environment you're using, the specifics of how to escape properly will likely change.
In bash, you need to stick a backslash in front of the $:
```
-Wl,-R\$ORIGIN
```
Code::Blocks apparently also treats the $ as special. Then, whatever subprocess controller Code::Blocks sends the command to treats the backslash as special. So, both the backslash and the $ need to be doubled up to get escaped properly. Therefore, in Code::Blocks linker settings, you need to specify:
```
-Wl,-R\\$$ORIGIN
```
...which outputs:
```
-Wl,-R\\$ORIGIN
```
...to the build log, but the shell actually gets sent:
```
-Wl,-R\$ORIGIN
```
...which as mentioned above produces the desired result.
What a pain.
|
230,382 |
<p>The print functionality of Excel (using VBA) is extremely slow. I'm hoping someone has a way of speeding the printing up (without using the Excel 4 Macro trick). Here's how I do it now:</p>
<pre><code>Application.ScreenUpdating = False
With ActiveSheet.PageSetup
-various setup statements which I've already minimized-
End With
ActiveSheet.PrintOut
Application.ScreenUpdating = True
</code></pre>
|
[
{
"answer_id": 231145,
"author": "Mike Rosenblum",
"author_id": 10429,
"author_profile": "https://Stackoverflow.com/users/10429",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, the PageSetup properties are very slow when you set them.</p>\n\n<p>You have already set <code>Application.ScreenUpdating = False</code>, which is good, but an equally (or more) important step in this case is to set <code>Application.Calculation = xlCalculationManual</code>. (It is best if you save these settings and then restore them to the original at the end.)</p>\n\n<p>Additionally, the property get for each PageSetup property is very fast, while it is only the property set that is so slow. Therefore, you should test the new property setting to make sure it isn't already the same as the existing property value in order to prevent an unnecessary (and expensive) call.</p>\n\n<p>With all this in mind, you should be able to use code that looks something like the following:</p>\n\n<pre><code>Dim origScreenUpdating As Boolean\norigScreenUpdating = Application.ScreenUpdating\nApplication.ScreenUpdating = False\n\nDim origCalcMode As xlCalculation\norigCalcMode = Application.Calculation\nApplication.Calculation = xlCalculationManual\n\nWith ActiveSheet.PageSetup\n If .PrintHeadings <> False Then .PrintHeadings = False\n If .PrintGridlines <> False Then .PrintGridlines = False\n If .PrintComments <> xlPrintNoComments Then .PrintComments = xlPrintNoComments\n ' Etc...\nEnd With\n\nApplication.ScreenUpdating = origScreenUpdating\nApplication.Calculation = origCalcMode\n</code></pre>\n\n<p><em>Edit: A couple of updates:</em> </p>\n\n<ol>\n<li><p>For Excel 2010 and above you can make use of the 'Application.PrintCommunication' property, while for Excel 2007 and below, you can make use of 'ExecuteExcel4Macro'. For more details, see <a href=\"http://blogs.msdn.com/excel/archive/2010/02/16/migrating-excel-4-macros-to-vba.aspx\" rel=\"noreferrer\">Migrating Excel 4 Macros to VBA</a>.</p></li>\n<li><p>For Excel 2007 and below, another interesting trick is to temporarily assign the printer driver to the 'Microsoft XPS Document Writer' and then set it back. Printing speed can improve by 3x. See: <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/8b2a0988-7d09-4abf-a4d3-76e81f708d40\" rel=\"noreferrer\">Slow Excel PageSetup Methods</a>.</p></li>\n</ol>\n\n<p>Hope this helps...</p>\n"
},
{
"answer_id": 284583,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>if you want to have basicly the same page settings for every tab in a workbook can you speed things up by setting up one workshet and then copying that worksheet's settings somehow to the other worksheets? Is this possible?</p>\n"
},
{
"answer_id": 866391,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In furthering Michael's post and answering @rhc's question, the following code may also help you if need to copy Page Setup customizations from a single worksheet to multiple worksheets in a workbook:</p>\n\n<pre><code>Public Sub CopyPageSetupToAll(ByRef SourceSheet As Worksheet)\n ' Raise error if invalid source sheet is passed to procedure\n '\n If (SourceSheet Is Nothing) Then\n Err.Raise _\n Number:=vbErrorObjectVariableNotSet, _\n Source:=\"CopyPageSetupToAll\", _\n Description:=\"Unable to copy Page Setup settings: \" _\n & \"invalid reference to source sheet.\"\n Exit Sub\n End If\n\n SourceSheet.Activate\n\n With SourceSheet.PageSetup\n ' ...\n ' place PageSetup customizations here\n ' ...\n End With\n\n SourceSheet.Parent.Worksheets.Select\n Application.SendKeys \"{ENTER}\", True\n Application.Dialogs(xlDialogPageSetup).Show\nEnd Sub\n</code></pre>\n\n<p>Alternatively, you could also modify the procedure to create a temporary worksheet to host your Page Setup changes, and then propagate those changes out to the other worksheets in your workbook:</p>\n\n<pre><code>Public Sub CopyPageSetupToAll(ByRef SourceBook As Workbook)\n Dim tempSheet As Worksheet\n\n ' Raise error if invalid workbook is passed to procedure\n '\n If (SourceBook Is Nothing) Then\n Err.Raise _\n Number:=vbErrorObjectVariableNotSet, _\n Source:=\"CopyPageSetupToAll\", _\n Description:=\"Unable to copy Page Setup settings: \" _\n & \"invalid reference to source workbook.\"\n Exit Sub\n End If\n\n Set tempSheet = SourceBook.Worksheets.Add\n\n tempSheet.Activate\n\n With tempSheet.PageSetup\n ' ...\n ' place PageSetup customizations here\n ' ...\n End With\n\n SourceBook.Worksheets.Select\n Application.SendKeys \"{ENTER}\", True\n Application.Dialogs(xlDialogPageSetup).Show\n tempSheet.Delete\n\n Set tempSheet = Nothing\nEnd Sub\n</code></pre>\n\n<p>Due to the use of the <code>SendKeys()</code> function and <code>Application.Dialogs</code> functionality, this code does not offer the cleanest possible solution. However, it gets the job done. :)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
] |
The print functionality of Excel (using VBA) is extremely slow. I'm hoping someone has a way of speeding the printing up (without using the Excel 4 Macro trick). Here's how I do it now:
```
Application.ScreenUpdating = False
With ActiveSheet.PageSetup
-various setup statements which I've already minimized-
End With
ActiveSheet.PrintOut
Application.ScreenUpdating = True
```
|
Yes, the PageSetup properties are very slow when you set them.
You have already set `Application.ScreenUpdating = False`, which is good, but an equally (or more) important step in this case is to set `Application.Calculation = xlCalculationManual`. (It is best if you save these settings and then restore them to the original at the end.)
Additionally, the property get for each PageSetup property is very fast, while it is only the property set that is so slow. Therefore, you should test the new property setting to make sure it isn't already the same as the existing property value in order to prevent an unnecessary (and expensive) call.
With all this in mind, you should be able to use code that looks something like the following:
```
Dim origScreenUpdating As Boolean
origScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = False
Dim origCalcMode As xlCalculation
origCalcMode = Application.Calculation
Application.Calculation = xlCalculationManual
With ActiveSheet.PageSetup
If .PrintHeadings <> False Then .PrintHeadings = False
If .PrintGridlines <> False Then .PrintGridlines = False
If .PrintComments <> xlPrintNoComments Then .PrintComments = xlPrintNoComments
' Etc...
End With
Application.ScreenUpdating = origScreenUpdating
Application.Calculation = origCalcMode
```
*Edit: A couple of updates:*
1. For Excel 2010 and above you can make use of the 'Application.PrintCommunication' property, while for Excel 2007 and below, you can make use of 'ExecuteExcel4Macro'. For more details, see [Migrating Excel 4 Macros to VBA](http://blogs.msdn.com/excel/archive/2010/02/16/migrating-excel-4-macros-to-vba.aspx).
2. For Excel 2007 and below, another interesting trick is to temporarily assign the printer driver to the 'Microsoft XPS Document Writer' and then set it back. Printing speed can improve by 3x. See: [Slow Excel PageSetup Methods](http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/8b2a0988-7d09-4abf-a4d3-76e81f708d40).
Hope this helps...
|
230,389 |
<p>I am new to jmock and trying to mock an HttpSession. I am getting:</p>
<p>java.lang.AssertionError: unexpected invocation: httpServletRequest.getSession()
no expectations specified: did you...
- forget to start an expectation with a cardinality clause?
- call a mocked method to specify the parameter of an expectation?</p>
<p>the test method:</p>
<p>@Test</p>
<pre><code>public void testDoAuthorization(){
final HttpServletRequest request = context.mock(HttpServletRequest.class);
final HttpSession session = request.getSession();
context.checking(new Expectations(){{
one(request).getSession(true); will(returnValue(session));
}});
assertTrue(dwnLoadCel.doAuthorization(session));
}
</code></pre>
<p>I have done a bit of searching and it isn't clear to me still how this is done. Feels like I am missing some small piece. Anyone with experience in this can just point me in the right direction.
thanks</p>
|
[
{
"answer_id": 230471,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<p>I think you need to tell the JMock context how many times you expect the method to be called before you actually go ahead and call it.</p>\n\n<pre><code>final HttpServletRequest request = context.mock(HttpServletRequest.class);\n\ncontext.checking(new Expectations(){{\n one(request).getSession(true); will(returnValue(session));\n}});\n\nfinal HttpSession session = request.getSession();\n</code></pre>\n\n<p>I'm not super familiar with JMock but do you actually care in your <code>dwnLoadCel</code> unit test how many times certain methods in the mocked object are called? Or are you just trying to test your class that depends on a HttpSession without an actual Session? If it's the latter than I think that JMock is overkill for you.</p>\n\n<p>You might want to look into either creating a class that implements the <code>HttpSession</code> interface yourself for the purposes of unit testing only (a stub), and running your tests off of that, or you should take a look at <code>dwnLoadCel</code> and determine if it <em>really</em> needs to have a reference to the HttpSession, or if it just needs some properties within the HttpSession. Refactor <code>dwnLoadCel</code> to only depend on what it actually needs (a <code>Map</code> or a certain parameter value within the Session object) - this will make your unit test easier (the dependency on the servlet container goes bye-bye).</p>\n\n<p>I think that you have some level of dependency injection in your class being tested already, but you might be dependent on too broad of an object. <a href=\"http://googletesting.blogspot.com/\" rel=\"nofollow noreferrer\">The Google Test Blog</a> has had <a href=\"http://googletesting.blogspot.com/2008/10/dependency-injection-myth-reference.html\" rel=\"nofollow noreferrer\">a lot</a> <a href=\"http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/\" rel=\"nofollow noreferrer\">of excellent</a> <a href=\"http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/\" rel=\"nofollow noreferrer\">articles</a> on DI lately that you might find useful (I sure have).</p>\n"
},
{
"answer_id": 231134,
"author": "Kris Pruden",
"author_id": 16977,
"author_profile": "https://Stackoverflow.com/users/16977",
"pm_score": 3,
"selected": true,
"text": "<p>You don't need to mock the request object. Since the method you're testing (<code>dwnLoadCel.doAuthorization()</code>) only depends on an <code>HttpSession</code> object, that is what you should mock. So your code would look like this:</p>\n\n<pre><code>public void testDoAuthorization(){\n final HttpSession session = context.mock(HttpSession.class);\n\n context.checking(new Expectations(){{\n // ???\n }});\n\n assertTrue(dwnLoadCel.doAuthorization(session));\n</code></pre>\n\n<p>}</p>\n\n<p>The question becomes: what do you expect the SUT to actually <em>do</em> with the session object? You need to express in your expectations the calls to <code>session</code> and their corresponding return values that are supposed to result in <code>doAuthorization</code> returning <code>true</code>.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3034/"
] |
I am new to jmock and trying to mock an HttpSession. I am getting:
java.lang.AssertionError: unexpected invocation: httpServletRequest.getSession()
no expectations specified: did you...
- forget to start an expectation with a cardinality clause?
- call a mocked method to specify the parameter of an expectation?
the test method:
@Test
```
public void testDoAuthorization(){
final HttpServletRequest request = context.mock(HttpServletRequest.class);
final HttpSession session = request.getSession();
context.checking(new Expectations(){{
one(request).getSession(true); will(returnValue(session));
}});
assertTrue(dwnLoadCel.doAuthorization(session));
}
```
I have done a bit of searching and it isn't clear to me still how this is done. Feels like I am missing some small piece. Anyone with experience in this can just point me in the right direction.
thanks
|
You don't need to mock the request object. Since the method you're testing (`dwnLoadCel.doAuthorization()`) only depends on an `HttpSession` object, that is what you should mock. So your code would look like this:
```
public void testDoAuthorization(){
final HttpSession session = context.mock(HttpSession.class);
context.checking(new Expectations(){{
// ???
}});
assertTrue(dwnLoadCel.doAuthorization(session));
```
}
The question becomes: what do you expect the SUT to actually *do* with the session object? You need to express in your expectations the calls to `session` and their corresponding return values that are supposed to result in `doAuthorization` returning `true`.
|
230,397 |
<p>I am writing a DB upgrade script that will check to see if an index has the right two columns defined. If it doesn't, or if it only has one of them, then I will DROP it (is there a way to ALTER an index?) and then recreate it with both.</p>
|
[
{
"answer_id": 230442,
"author": "Ed Altorfer",
"author_id": 26552,
"author_profile": "https://Stackoverflow.com/users/26552",
"pm_score": 4,
"selected": true,
"text": "<p>I don't have a database immediately on-hand to test this, but you should be able to see if a column exists in an index by using the following IF EXISTS statement.</p>\n\n<p>I'm not sure whether you can alter an index on the fly.</p>\n\n<pre><code>IF EXISTS\n(\n SELECT MyIndex.Name AS IndexName, \n Columns.name AS ColumnName \n FROM sys.indexes MyIndex\n INNER JOIN sys.index_columns IndexColumns \n ON MyIndex.index_id = IndexColumns.index_id\n AND MyIndex.object_id = IndexColumns.object_id \n INNER JOIN sys.columns Columns\n ON Columns.column_id = IndexColumns.column_id \n AND IndexColumns.object_id = Columns.object_id \n WHERE Columns.name = 'ColumnName'\n AND MyIndex.Name='IX_MyIndexName'\n)\n</code></pre>\n"
},
{
"answer_id": 230567,
"author": "skb",
"author_id": 14101,
"author_profile": "https://Stackoverflow.com/users/14101",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for your help, Ed. Here is the solution I wrote using yours as a start. It has been verified. Basically it has all of the correct joins.</p>\n\n<pre>\n<code>\nIF EXISTS\n(\n SELECT i.Name AS IndexName, c.Name AS ColumnName\n FROM sys.indexes i\n JOIN sys.index_columns ic\n ON i.object_id = ic.object_id AND i.index_id = ic.index_id\n JOIN sys.columns c\n ON ic.object_id = c.object_id AND c.column_id = ic.column_id\n WHERE c.Name = 'MyColumnName' AND i.Name='MyIndexName'\n)\n</code>\n</pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
] |
I am writing a DB upgrade script that will check to see if an index has the right two columns defined. If it doesn't, or if it only has one of them, then I will DROP it (is there a way to ALTER an index?) and then recreate it with both.
|
I don't have a database immediately on-hand to test this, but you should be able to see if a column exists in an index by using the following IF EXISTS statement.
I'm not sure whether you can alter an index on the fly.
```
IF EXISTS
(
SELECT MyIndex.Name AS IndexName,
Columns.name AS ColumnName
FROM sys.indexes MyIndex
INNER JOIN sys.index_columns IndexColumns
ON MyIndex.index_id = IndexColumns.index_id
AND MyIndex.object_id = IndexColumns.object_id
INNER JOIN sys.columns Columns
ON Columns.column_id = IndexColumns.column_id
AND IndexColumns.object_id = Columns.object_id
WHERE Columns.name = 'ColumnName'
AND MyIndex.Name='IX_MyIndexName'
)
```
|
230,401 |
<p>I'm trying to use jQuery to get data from an ASP.NET web service (SharePoint Server 2007 lists.asmx), but any call to a web service will really help as a first step in that direction.</p>
|
[
{
"answer_id": 230408,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 3,
"selected": false,
"text": "<p>Here is an example to call your webservice using jQuery.get:</p>\n\n<pre><code>$.get(\"http://domain.com/webservice.asmx\", { name: \"John\", time: \"2pm\" },\n function(data){\n alert(\"Data Loaded: \" + data);\n });\n</code></pre>\n\n<p>In the example above, we call \"webservice.asmx\", passing two parameters: name and time. Then, getting the service output in the call back function.</p>\n"
},
{
"answer_id": 230605,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know about that specific SharePoint web service, but you can decorate a page method or a web service with <code><WebMethod()></code> (in VB.NET) to ensure that it serializes to JSON. You can probably just wrap the method that webservice.asmx uses internally, in your own web service.</p>\n\n<p>Dave Ward has <a href=\"http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/\" rel=\"nofollow noreferrer\">a nice walkthrough</a> on this.</p>\n"
},
{
"answer_id": 341165,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I quite often use ajaxpro along with jQuery. ajaxpro lets me call .NET functions from JavaScript and I use jQuery for the rest.</p>\n"
},
{
"answer_id": 485495,
"author": "Brandon Joyce",
"author_id": 54050,
"author_profile": "https://Stackoverflow.com/users/54050",
"pm_score": 1,
"selected": false,
"text": "<p>I have a decent example in <em><a href=\"http://www.sonerdy.com/jquery-ajax-and-asmx/\" rel=\"nofollow noreferrer\">jQuery AJAX and ASMX</a></em> on using the jQuery AJAX call with asmx web services... </p>\n\n<p>There is a line of code to uncommment in order to have it return JSON.</p>\n"
},
{
"answer_id": 485536,
"author": "Bobby Borszich",
"author_id": 35585,
"author_profile": "https://Stackoverflow.com/users/35585",
"pm_score": 7,
"selected": true,
"text": "<p>I use this method as a wrapper so that I can send parameters. Also using the variables in the top of the method allows it to be minimized at a higher ratio and allows for some code reuse if making multiple similar calls.</p>\n\n<pre><code>function InfoByDate(sDate, eDate){\n var divToBeWorkedOn = \"#AjaxPlaceHolder\";\n var webMethod = \"http://MyWebService/Web.asmx/GetInfoByDates\";\n var parameters = \"{'sDate':'\" + sDate + \"','eDate':'\" + eDate + \"'}\";\n\n $.ajax({\n type: \"POST\",\n url: webMethod,\n data: parameters,\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function(msg) {\n $(divToBeWorkedOn).html(msg.d);\n },\n error: function(e){\n $(divToBeWorkedOn).html(\"Unavailable\");\n }\n });\n}\n</code></pre>\n\n<p>I hope that helps.</p>\n\n<p>Please note that this requires the 3.5 framework to expose JSON webmethods that can be consumed in this manner.</p>\n"
},
{
"answer_id": 6921657,
"author": "Kaveh",
"author_id": 875855,
"author_profile": "https://Stackoverflow.com/users/875855",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$.ajax({\n type: 'POST',\n url: 'data.asmx/getText',\n data: {'argInput' : 'input arg(s)'},\n complete: function(xData, status) {\n $('#txt').html($(xData.responseXML).text()); // result\n }\n});\n</code></pre>\n"
},
{
"answer_id": 16394477,
"author": "Vadim Gremyachev",
"author_id": 1375553,
"author_profile": "https://Stackoverflow.com/users/1375553",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://spservices.codeplex.com/\" rel=\"nofollow\">SPServices</a> is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use</p>\n\n<p>It is <a href=\"http://spservices.codeplex.com/wikipage?title=Glossary#Certification\" rel=\"nofollow\">certified</a> for SharePoint 2007 </p>\n\n<p>The list of supported operations for Lists.asmx could be found <a href=\"http://spservices.codeplex.com/wikipage?title=Lists&referringTitle=%24%28%29.SPServices\" rel=\"nofollow\">here</a> </p>\n\n<h2>Example</h2>\n\n<p>In this example, we're grabbing all of the items in the Announcements list and displaying the Titles in a bulleted list in the tasksUL div:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"filelink/jquery-1.6.1.min.js\"></script>\n<script type=\"text/javascript\" src=\"filelink/jquery.SPServices-0.6.2.min.js\"></script>\n<script language=\"javascript\" type=\"text/javascript\">\n\n$(document).ready(function() {\n $().SPServices({\n operation: \"GetListItems\",\n async: false,\n listName: \"Announcements\",\n CAMLViewFields: \"<ViewFields><FieldRef Name='Title' /></ViewFields>\",\n completefunc: function (xData, Status) {\n $(xData.responseXML).SPFilterNode(\"z:row\").each(function() {\n var liHtml = \"<li>\" + $(this).attr(\"ows_Title\") + \"</li>\";\n $(\"#tasksUL\").append(liHtml);\n });\n }\n });\n});\n</script>\n<ul id=\"tasksUL\"/>\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30867/"
] |
I'm trying to use jQuery to get data from an ASP.NET web service (SharePoint Server 2007 lists.asmx), but any call to a web service will really help as a first step in that direction.
|
I use this method as a wrapper so that I can send parameters. Also using the variables in the top of the method allows it to be minimized at a higher ratio and allows for some code reuse if making multiple similar calls.
```
function InfoByDate(sDate, eDate){
var divToBeWorkedOn = "#AjaxPlaceHolder";
var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$(divToBeWorkedOn).html(msg.d);
},
error: function(e){
$(divToBeWorkedOn).html("Unavailable");
}
});
}
```
I hope that helps.
Please note that this requires the 3.5 framework to expose JSON webmethods that can be consumed in this manner.
|
230,409 |
<p>In my <a href="https://stackoverflow.com/questions/222442/sql-server-running-large-script-files">eternal</a> <a href="https://stackoverflow.com/questions/224830/how-do-i-set-a-sql-server-scripts-timeout-from-within-the-script">saga</a> to insert 1.4 million rows of data from a SQL script, I've written a basic WinForms app that takes each line of the script and executes it individually.</p>
<p>However, because the original script contained</p>
<pre><code>SET IDENTITY_INSERT [Table] OFF
</code></pre>
<p>and SET is a session-wide command, this setting is getting lost on every SQL call, meaning that each line is failing. Is there a way to set IDENTITY_INSERT off for the whole table, database-wide just so I can make these individual calls without them failing? Or perhaps I can tell it to ignore the identity specification by appending a command to each line?</p>
|
[
{
"answer_id": 230423,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms188365.aspx\" rel=\"noreferrer\">BULK INSERT</a> won't work for you? Or the SQL Server Import/Export Wizard (<a href=\"http://www.databasejournal.com/features/mssql/article.php/3580216\" rel=\"noreferrer\">here</a> or <a href=\"http://technet.microsoft.com/en-us/library/ms141209.aspx\" rel=\"noreferrer\">here</a>)? I know import/export can turn off identity insert for the whole import. I'm reasonably certain you can do it just prior to BULK INSERT</p>\n"
},
{
"answer_id": 230489,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that IDENTITY INSERT can only be overridden one table at a time, per session.</p>\n\n<p>You will have to maybe batch up 2 or 300 insert statements at a time and precede each batch with the ident insert. </p>\n\n<p>so the app will execute a block like this....</p>\n\n<pre><code>SET IDENTITY_INSERT [Table] OFF;\nINSERT INTO TABLE VALUES (1, 'a');\nINSERT INTO TABLE VALUES (2, 'b');\nINSERT INTO TABLE VALUES (3, 'c');\nINSERT INTO TABLE VALUES (4, 'd');\nINSERT INTO TABLE VALUES (5, 'e');\nSET IDENTITY_INSERT [Table] ON;\n</code></pre>\n"
},
{
"answer_id": 230708,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 0,
"selected": false,
"text": "<p>Is anything else going to be accessing/inserting to the table while this is 1.4 million insert job is going on.</p>\n\n<p>If not, you could simply Disable the Identity on the PK column for the duration of the job?</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
In my [eternal](https://stackoverflow.com/questions/222442/sql-server-running-large-script-files) [saga](https://stackoverflow.com/questions/224830/how-do-i-set-a-sql-server-scripts-timeout-from-within-the-script) to insert 1.4 million rows of data from a SQL script, I've written a basic WinForms app that takes each line of the script and executes it individually.
However, because the original script contained
```
SET IDENTITY_INSERT [Table] OFF
```
and SET is a session-wide command, this setting is getting lost on every SQL call, meaning that each line is failing. Is there a way to set IDENTITY\_INSERT off for the whole table, database-wide just so I can make these individual calls without them failing? Or perhaps I can tell it to ignore the identity specification by appending a command to each line?
|
[BULK INSERT](http://msdn.microsoft.com/en-us/library/ms188365.aspx) won't work for you? Or the SQL Server Import/Export Wizard ([here](http://www.databasejournal.com/features/mssql/article.php/3580216) or [here](http://technet.microsoft.com/en-us/library/ms141209.aspx))? I know import/export can turn off identity insert for the whole import. I'm reasonably certain you can do it just prior to BULK INSERT
|
230,411 |
<p>I want yo use the EXSLT - DYN:EVALUATE in a style sheet. I have added the names pace but I don't know where the .xsl file I need to import is. I don't believe I have XALAN installed to point the import to. How would I install this? Once installed and I point it to the .xsl will it pick up the function and apply it? I am running Windows. The XSLT file is included at the top of the XML document.</p>
<p>Thanks</p>
<p>Pete</p>
|
[
{
"answer_id": 232526,
"author": "GerG",
"author_id": 17249,
"author_profile": "https://Stackoverflow.com/users/17249",
"pm_score": 4,
"selected": true,
"text": "<p>Xalan has the EXSL dyn:evaluate function built-in, you don't need to import anything in order to use it. You just need to declare the namespace. I'll give a small example:</p>\n\n<p><em>input.xml</em>:</p>\n\n<pre><code><root>\n<foo>I am foo</foo> \n<bar>I am bar</bar> \n</root>\n</code></pre>\n\n<p><em>dyn_evaluate.xsl</em>:</p>\n\n<pre><code><xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" \n xmlns:dyn=\"http://exslt.org/dynamic\"\n extension-element-prefixes=\"dyn\">\n\n <xsl:param name=\"path\"/>\n\n <xsl:output method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:value-of select=\"dyn:evaluate($path)\"/>\n </xsl:template>\n\n</xsl:stylesheet>\n</code></pre>\n\n<p>Running</p>\n\n<pre><code>xalan.exe -p path '/root/foo' input.xml dyn_evaluate.xsl\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>I am foo\n</code></pre>\n\n<p>Running</p>\n\n<p>xalan.exe -p path '/root/bar' input.xml dyn_evaluate.xsl</p>\n\n<p>gives</p>\n\n<pre><code>I am bar\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 232807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>How would you call this from a JSP page? The JSP serves up the XML and currently attaches the style sheet to the XML page and servers the result.</p>\n"
},
{
"answer_id": 396576,
"author": "alamar",
"author_id": 36498,
"author_profile": "https://Stackoverflow.com/users/36498",
"pm_score": 0,
"selected": false,
"text": "<p>You can't, because if you'll serve the client with XML page with attached stylesheet, this wouldn't work. Browsers don't support exslt.</p>\n\n<p>However, if you do XSLT processing on server (with xalan) you can get it to work, but I don't understand how you combine xslt with jsp.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want yo use the EXSLT - DYN:EVALUATE in a style sheet. I have added the names pace but I don't know where the .xsl file I need to import is. I don't believe I have XALAN installed to point the import to. How would I install this? Once installed and I point it to the .xsl will it pick up the function and apply it? I am running Windows. The XSLT file is included at the top of the XML document.
Thanks
Pete
|
Xalan has the EXSL dyn:evaluate function built-in, you don't need to import anything in order to use it. You just need to declare the namespace. I'll give a small example:
*input.xml*:
```
<root>
<foo>I am foo</foo>
<bar>I am bar</bar>
</root>
```
*dyn\_evaluate.xsl*:
```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:dyn="http://exslt.org/dynamic"
extension-element-prefixes="dyn">
<xsl:param name="path"/>
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:value-of select="dyn:evaluate($path)"/>
</xsl:template>
</xsl:stylesheet>
```
Running
```
xalan.exe -p path '/root/foo' input.xml dyn_evaluate.xsl
```
gives
```
I am foo
```
Running
xalan.exe -p path '/root/bar' input.xml dyn\_evaluate.xsl
gives
```
I am bar
```
Hope this helps.
|
230,454 |
<p>What would be the best way to fill an array from user input?</p>
<p>Would a solution be showing a prompt message and then get the values from from the user?</p>
|
[
{
"answer_id": 230463,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 7,
"selected": true,
"text": "<pre><code>string []answer = new string[10];\nfor(int i = 0;i<answer.length;i++)\n{\n answer[i]= Console.ReadLine();\n}\n</code></pre>\n"
},
{
"answer_id": 230485,
"author": "Ed Altorfer",
"author_id": 26552,
"author_profile": "https://Stackoverflow.com/users/26552",
"pm_score": 2,
"selected": false,
"text": "<p>C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.</p>\n\n<p>If you add a reference to \"Microsoft Visual Basic .NET Runtime\" and then insert:</p>\n\n<pre><code>using Microsoft.VisualBasic;\n</code></pre>\n\n<p>You can do the following:</p>\n\n<pre><code>List<string> responses = new List<string>();\nstring response = \"\";\n\nwhile(!(response = Interaction.InputBox(\"Please enter your information\",\n \"Window Title\",\n \"Default Text\",\n xPosition,\n yPosition)).equals(\"\"))\n{\n responses.Add(response);\n}\n\nresponses.ToArray();\n</code></pre>\n"
},
{
"answer_id": 230583,
"author": "Coderer",
"author_id": 26286,
"author_profile": "https://Stackoverflow.com/users/26286",
"pm_score": 3,
"selected": false,
"text": "<p>Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.</p>\n\n<p>If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use</p>\n\n<pre><code>string foo = Console.ReadLine();\nstring[] tokens = foo.Split(\",\");\nList<int> nums = new List<int>();\nint oneNum;\nforeach(string s in tokens)\n{\n if(Int32.TryParse(s, out oneNum))\n nums.Add(oneNum);\n}\n</code></pre>\n\n<p>Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.</p>\n"
},
{
"answer_id": 230611,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 0,
"selected": false,
"text": "<p>Add the input values to a List and when you are done use List.ToArray() to get an array with the values.</p>\n"
},
{
"answer_id": 230781,
"author": "Stefan",
"author_id": 30604,
"author_profile": "https://Stackoverflow.com/users/30604",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>array[i] = Convert.ToDouble(Console.Readline());\n</code></pre>\n\n<p>You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.</p>\n"
},
{
"answer_id": 231047,
"author": "arin",
"author_id": 30858,
"author_profile": "https://Stackoverflow.com/users/30858",
"pm_score": 2,
"selected": false,
"text": "<h1>I've done it finaly check it and if there is a better way tell me guys</h1>\n\n<pre><code> static void Main()\n {\n double[] array = new double[6];\n Console.WriteLine(\"Please Sir Enter 6 Floating numbers\");\n for (int i = 0; i < 6; i++)\n {\n array[i] = Convert.ToDouble(Console.ReadLine());\n }\n\n double sum = 0;\n\n foreach (double d in array)\n {\n sum += d;\n }\n double average = sum / 6;\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"The Values you've entered are\");\n Console.WriteLine(\"{0}{1,8}\", \"index\", \"value\");\n for (int counter = 0; counter < 6; counter++)\n Console.WriteLine(\"{0,5}{1,8}\", counter, array[counter]);\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"The average is ;\");\n Console.WriteLine(average);\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"would you like to search for a certain elemnt ? (enter yes or no)\");\n string answer = Console.ReadLine();\n switch (answer)\n {\n case \"yes\":\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"please enter the array index you wish to get the value of it\");\n int index = Convert.ToInt32(Console.ReadLine());\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"The Value of the selected index is:\");\n Console.WriteLine(array[index]);\n break;\n\n case \"no\":\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"HAVE A NICE DAY SIR\");\n break;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 231208,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>It made a lot more sense to add this as an answer to <a href=\"https://stackoverflow.com/questions/230454/how-to-fill-an-array-from-user-input-c#231047\">arin's code</a> than to keep doing it in comments...</p>\n\n<p>1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See <a href=\"http://pobox.com/~skeet/csharp/floatingpoint.html\" rel=\"nofollow noreferrer\">http://pobox.com/~skeet/csharp/floatingpoint.html</a> and <a href=\"http://pobox.com/~skeet/csharp/decimal.html\" rel=\"nofollow noreferrer\">http://pobox.com/~skeet/csharp/decimal.html</a> for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers \"naturally\" think about numbers, which is why it's faster - but that's not relevant here.</p>\n\n<p>2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an <code>out</code> parameter to give the result. If you haven't started learning about <code>out</code> parameters yet, it might be worth ignoring this point for the moment.</p>\n\n<p>3) It's only a little point, but I think it's wise to have braces round all \"for\"/\"if\" (etc) bodies, so I'd change this:</p>\n\n<pre><code>for (int counter = 0; counter < 6; counter++)\n Console.WriteLine(\"{0,5}{1,8}\", counter, array[counter]);\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>for (int counter = 0; counter < 6; counter++)\n{\n Console.WriteLine(\"{0,5}{1,8}\", counter, array[counter]);\n}\n</code></pre>\n\n<p>It makes the block clearer, and means you don't accidentally write:</p>\n\n<pre><code>for (int counter = 0; counter < 6; counter++)\n Console.WriteLine(\"{0,5}{1,8}\", counter, array[counter]);\n Console.WriteLine(\"----\"); // This isn't part of the for loop!\n</code></pre>\n\n<p>4) Your switch statement doesn't have a <code>default</code> case - so if the user types anything other than \"yes\" or \"no\" it will just ignore them and quit. You might want to have something like:</p>\n\n<pre><code>bool keepGoing = true;\nwhile (keepGoing)\n{\n switch (answer)\n {\n case \"yes\":\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"please enter the array index you wish to get the value of it\");\n int index = Convert.ToInt32(Console.ReadLine());\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"The Value of the selected index is:\");\n Console.WriteLine(array[index]);\n keepGoing = false;\n break;\n\n case \"no\":\n Console.WriteLine(\"===============================================\");\n Console.WriteLine(\"HAVE A NICE DAY SIR\");\n keepGoing = false;\n break;\n\n default:\n Console.WriteLine(\"Sorry, I didn't understand that. Please enter yes or no\");\n break;\n }\n}\n</code></pre>\n\n<p>5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:</p>\n\n<pre><code>// Or decimal, of course, if you've made the earlier selected change\ndouble sum = input.Sum();\n</code></pre>\n\n<p>Again, this is fairly advanced - don't worry about it for now!</p>\n"
},
{
"answer_id": 594489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>of course....Console.ReadLine always return string....so you have to convert type string to double</p>\n\n<p>array[i]=double.Parse(Console.ReadLine());</p>\n"
},
{
"answer_id": 1533644,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>readline is for string..\njust use read</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30858/"
] |
What would be the best way to fill an array from user input?
Would a solution be showing a prompt message and then get the values from from the user?
|
```
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
answer[i]= Console.ReadLine();
}
```
|
230,522 |
<p>I have a table with multiple rows. Each row is a form. I want to use JQuery to submit all the forms that have the check box checked. The form is posting to an IFrame so there is not much need for AJAX.</p>
<p>So far I have:</p>
<pre><code> $("form").submit();
</code></pre>
<p>which submits the form. but all forms. There is arbritary number of rows, could be 80-100.</p>
|
[
{
"answer_id": 230540,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>This is kinda a guess since I'm not sure of your layout, but here goes....</p>\n\n<pre><code>$(\"td > input:checked > form\").submit();\n</code></pre>\n"
},
{
"answer_id": 230551,
"author": "Nathan Strutz",
"author_id": 5918,
"author_profile": "https://Stackoverflow.com/users/5918",
"pm_score": 3,
"selected": true,
"text": "<p>Off the top of my head, you probably want something like this</p>\n\n<pre><code>$(\"input:checked\").parent(\"form\").submit();\n</code></pre>\n\n<p>This will find the checked form fields, traverse up to find the parent form object and submit that.</p>\n"
},
{
"answer_id": 230579,
"author": "Jeremy B.",
"author_id": 28567,
"author_profile": "https://Stackoverflow.com/users/28567",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure about submit, because I've done this in .post(), but here is what I've used to get what I want to send on the submission:</p>\n\n<pre><code>var formElements = $(\"form\").find(\"input:checked\").parent(\"td\").serialize();\n</code></pre>\n\n<p>you should be able to send back that variable.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
I have a table with multiple rows. Each row is a form. I want to use JQuery to submit all the forms that have the check box checked. The form is posting to an IFrame so there is not much need for AJAX.
So far I have:
```
$("form").submit();
```
which submits the form. but all forms. There is arbritary number of rows, could be 80-100.
|
Off the top of my head, you probably want something like this
```
$("input:checked").parent("form").submit();
```
This will find the checked form fields, traverse up to find the parent form object and submit that.
|
230,585 |
<p>I have the following code:</p>
<pre><code>class IncidentTag:
def __init__(self,tag):
self.tag = tag
def equals(self,obj):
return self.tag.equals(obj.tag)
def hashCode(self):
return self.tag.hashCode()
from java.lang import String
from java.util import HashMap
from java.util import HashSet
tag1 = IncidentTag(String("email"))
tag1copy = IncidentTag(String("email"))
tag2 = IncidentTag(String("notemail"))
print tag1.equals(tag1copy)
print tag2.equals(tag2)
print "Now with HashSet:"
hSet = HashSet()
hSet.add(tag1)
hSet.add(tag2)
print hSet.contains(tag1)
print hSet.contains(tag2)
print hSet.contains(tag1copy)
</code></pre>
<p>The output is:
1
1
Now with HashSet:
1
1
0</p>
<p>However, I would have expected the last line to be <code>true</code>(1) as well. Is there something obvious that I am missing.</p>
<p>(yes, I know that my <code>equals</code> method and <code>hashcode</code> methods do not take some issues into account... they are deliberately simple, but do let me know if the issues there are causing this problem.)</p>
|
[
{
"answer_id": 230656,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote equivalent code in Java and it does produce true for all three contains() calls. So I think this must be an oddity in Jython. Maybe the underlying Java objects are not exactly what you see them as in Python.</p>\n"
},
{
"answer_id": 230812,
"author": "dmeister",
"author_id": 4194,
"author_profile": "https://Stackoverflow.com/users/4194",
"pm_score": 4,
"selected": true,
"text": "<p>You shouldn't implemented the Java-Style equals and hashCode method, but instead the Python equivaltents <code>__eq__</code> and <code>__hash__</code>. Adding</p>\n\n<pre><code>def __hash__(self):\n return self.hashCode()\ndef __eq__(self, o):\n return self.equals(o)\n</code></pre>\n\n<p>helps.\nThese python methods are - as far as I know - dynamically bound to hashCode and equals() by Jython. This ensures that you can put Python classes into Java's collections.</p>\n\n<p>Now the code prints five \"1\".</p>\n"
},
{
"answer_id": 231762,
"author": "Chris Kessel",
"author_id": 29734,
"author_profile": "https://Stackoverflow.com/users/29734",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know Python, but it sure looks like the underlying Java object's equals() and hashcode() aren't honoring the required contract.</p>\n\n<ul>\n<li>Two objects if equals() must return the same hashcode(). </li>\n</ul>\n\n<p>It looks like that is violated. HashSets are first going to use the hashcode in the lookup to get the list the matching object would be in, then go through the list to find the one that's equal. If your hashcode isn't honoring the contract and they're returning different hashcodes, then it won't find it in the hashset even if they were equals() comparable.</p>\n\n<p>The default Java Object.hashcode() isn't going to return the same hashcode for 2 objects. You've got to override it.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432/"
] |
I have the following code:
```
class IncidentTag:
def __init__(self,tag):
self.tag = tag
def equals(self,obj):
return self.tag.equals(obj.tag)
def hashCode(self):
return self.tag.hashCode()
from java.lang import String
from java.util import HashMap
from java.util import HashSet
tag1 = IncidentTag(String("email"))
tag1copy = IncidentTag(String("email"))
tag2 = IncidentTag(String("notemail"))
print tag1.equals(tag1copy)
print tag2.equals(tag2)
print "Now with HashSet:"
hSet = HashSet()
hSet.add(tag1)
hSet.add(tag2)
print hSet.contains(tag1)
print hSet.contains(tag2)
print hSet.contains(tag1copy)
```
The output is:
1
1
Now with HashSet:
1
1
0
However, I would have expected the last line to be `true`(1) as well. Is there something obvious that I am missing.
(yes, I know that my `equals` method and `hashcode` methods do not take some issues into account... they are deliberately simple, but do let me know if the issues there are causing this problem.)
|
You shouldn't implemented the Java-Style equals and hashCode method, but instead the Python equivaltents `__eq__` and `__hash__`. Adding
```
def __hash__(self):
return self.hashCode()
def __eq__(self, o):
return self.equals(o)
```
helps.
These python methods are - as far as I know - dynamically bound to hashCode and equals() by Jython. This ensures that you can put Python classes into Java's collections.
Now the code prints five "1".
|
230,588 |
<p>I am trying to sort a list using delegates but I am getting a signature match error. The compiler says I cannot convert from an 'anonymous method' </p>
<pre><code>List<MyType> myList = GetMyList();
myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID < t2.ID); } );
</code></pre>
<p>What am I missing?</p>
<p>Here are some references I found and they do it the same way.</p>
<p><a href="http://www.developerfusion.com/code/5513/sorting-and-searching-using-c-lists/" rel="noreferrer">Developer Fusion Reference</a> </p>
<p><a href="http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx" rel="noreferrer">Microsoft Reference</a></p>
|
[
{
"answer_id": 230597,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 4,
"selected": false,
"text": "<p>The Sort doesn't take a binary predicate, it takes a <code>Comparison<T></code> delegate which returns an <code>int</code> not a <code>bool</code>.</p>\n\n<p>The return values are <code>0</code> for when the items are equal, <code><0</code> for when the first item is less than the second, and <code>>0</code> for when the first item is greater than the second.</p>\n"
},
{
"answer_id": 230620,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 7,
"selected": true,
"text": "<p>I think you want:</p>\n\n<pre><code>myList.Sort( delegate (MyType t1, MyType t2) \n { return (t1.ID.CompareTo(t2.ID)); } \n);\n</code></pre>\n\n<p>To sort you need something other than \"true/false\", you need to know if its equal to, greater than, or less than.</p>\n"
},
{
"answer_id": 230770,
"author": "David.Chu.ca",
"author_id": 62776,
"author_profile": "https://Stackoverflow.com/users/62776",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure if your ID property is the default value data type, such as Int or String. If the ID is an object reference type, that object should implement IComparer or IComparer.</p>\n"
},
{
"answer_id": 230783,
"author": "David.Chu.ca",
"author_id": 62776,
"author_profile": "https://Stackoverflow.com/users/62776",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry for previous post. The editor does not take < and > characters, and I did not notice the preview right under the editor. If the ID property is an object type, the object should implement IComparer or IComparer<T>.</p>\n"
},
{
"answer_id": 230824,
"author": "Coderer",
"author_id": 26286,
"author_profile": "https://Stackoverflow.com/users/26286",
"pm_score": 2,
"selected": false,
"text": "<p>In future, if you want to debug problems like this, I'd advocate breaking out the delegate definition from the Sort call, like this:</p>\n\n<pre><code>Comparison<MyType> c = delegate(MyType t1, MyType t2){ ... };\nmyList.Sort(c);\n</code></pre>\n\n<p>That way, you can see if the problem is in your method call, or in your delegate definition. Some people prefer to leave it this way (with a more descriptive name than \"c\", obviously) to make the code more readable. I could take it or leave it =-)</p>\n"
},
{
"answer_id": 231197,
"author": "David.Chu.ca",
"author_id": 62776,
"author_profile": "https://Stackoverflow.com/users/62776",
"pm_score": 1,
"selected": false,
"text": "<p>The way of obj.Sort(delegate(...)); is dynamic sorting in one place. If you have several places doing the same sorting or you need more flexible sorting, you may consider to create a class implementing IComparer<T>. Here is an example:</p>\n\n<pre><code>public class MyTypeComparer : IComparer<MyType>\n{\n public MyTypeComparer() // default comparer on ID\n { ... }\n\n public MyTypeComparer(bool desc) // default with order specified\n\n public MyTypeComparer(string sort, bool desc) // specified sort and order such as property name, true or false.\n { ... }\n\n public int Compare(MyType a, MyType b) // implement IComparer interface\n { ... } // this is real sorting codes\n}\n</code></pre>\n\n<p>and here is the example to use it:</p>\n\n<pre><code>List<MyType> myList = GetList();\nmyList.Sort(new MyTypeComparer());\n// myList.Sort(new MyTypeComparer(false));\n// myList.Sort(new MyTypeComparer(\"FirstName\", true));\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
I am trying to sort a list using delegates but I am getting a signature match error. The compiler says I cannot convert from an 'anonymous method'
```
List<MyType> myList = GetMyList();
myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID < t2.ID); } );
```
What am I missing?
Here are some references I found and they do it the same way.
[Developer Fusion Reference](http://www.developerfusion.com/code/5513/sorting-and-searching-using-c-lists/)
[Microsoft Reference](http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx)
|
I think you want:
```
myList.Sort( delegate (MyType t1, MyType t2)
{ return (t1.ID.CompareTo(t2.ID)); }
);
```
To sort you need something other than "true/false", you need to know if its equal to, greater than, or less than.
|
230,592 |
<p>Here's the XML code I'm working with:</p>
<pre><code><inventory>
<drink>
<lemonade supplier="mother" id="1">
<price>$2.50</price>
<amount>20</amount>
</lemonade>
<lemonade supplier="mike" id="4">
<price>$3.00</price>
<amount>20</amount>
</lemonade>
<pop supplier="store" id="2">
<price>$1.50</price>
<amount>10</amount>
</pop>
</drink>
</inventory>
</code></pre>
<p>Then I wrote a simple code to practice working with XPath:</p>
<pre><code><?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');
$xpathvar = new Domxpath($xmldoc);
$queryResult = $xpathvar->query('//lemonade/price');
foreach($queryResult as $result) {
echo $result->textContent;
}
?>
</code></pre>
<p>That code is working well, outputting all the lemonade price values as expected. Now when i change the query string to select only the elements with an attribute set to a certain value, like </p>
<blockquote>
<p>//lemonade[supplier="mother"]/price</p>
</blockquote>
<p>or </p>
<blockquote>
<p>//lemonade[id="1"]/price</p>
</blockquote>
<p>it won't work, no output at all. What am i doing wrong?</p>
|
[
{
"answer_id": 230609,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 6,
"selected": true,
"text": "<p>Try this: </p>\n\n<pre><code>//lemonade[@id=\"1\"]/price\n</code></pre>\n\n<p>or </p>\n\n<pre><code>//lemonade[@supplier=\"mother\"]/price\n</code></pre>\n\n<p>Without the \"@\" it looks for child elements with that name instead of attributes.</p>\n"
},
{
"answer_id": 230619,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 3,
"selected": false,
"text": "<p>you have to use the @ sign to indicate attribute within the predicate like so: <code>//lemonade[@supplier=\"mother\"]/price</code>, that's all.</p>\n"
},
{
"answer_id": 432838,
"author": "Tirno",
"author_id": 9886,
"author_profile": "https://Stackoverflow.com/users/9886",
"pm_score": 3,
"selected": false,
"text": "<p>This is only tangentially related, but when you use XPath on a document for which you know the structure, <em>don't</em> use \"//some-element-name\". It's very nice for a quick example, but when you hit a huge xml file with that query, particularly if it is followed by something complex, you will quickly run into performance issues.</p>\n\n<p>inventory/drink/lemonade[@supplier=\"mother\"]/price</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27090/"
] |
Here's the XML code I'm working with:
```
<inventory>
<drink>
<lemonade supplier="mother" id="1">
<price>$2.50</price>
<amount>20</amount>
</lemonade>
<lemonade supplier="mike" id="4">
<price>$3.00</price>
<amount>20</amount>
</lemonade>
<pop supplier="store" id="2">
<price>$1.50</price>
<amount>10</amount>
</pop>
</drink>
</inventory>
```
Then I wrote a simple code to practice working with XPath:
```
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');
$xpathvar = new Domxpath($xmldoc);
$queryResult = $xpathvar->query('//lemonade/price');
foreach($queryResult as $result) {
echo $result->textContent;
}
?>
```
That code is working well, outputting all the lemonade price values as expected. Now when i change the query string to select only the elements with an attribute set to a certain value, like
>
> //lemonade[supplier="mother"]/price
>
>
>
or
>
> //lemonade[id="1"]/price
>
>
>
it won't work, no output at all. What am i doing wrong?
|
Try this:
```
//lemonade[@id="1"]/price
```
or
```
//lemonade[@supplier="mother"]/price
```
Without the "@" it looks for child elements with that name instead of attributes.
|
230,636 |
<p>I am trying to implement the following functionality:</p>
<pre><code>class WeightResolver {
WeightMonitor _source;
bool _cancelled;
Weight _threshold;
public Cancel() {
_cancelled = true;
}
public Weight Resolve(){
_cancelled = false;
while(_source.CurrentWeight < threshold ) {
if(_cancelled)
throw new CancelledOperationException();
// Wait until one of the above conditions is met
}
return _source.CurrentWeight
}
}
</code></pre>
<p>However I am running into trouble managing my threads. For example, the Cancel method is registered via an event and Resolve invoked as follows:</p>
<pre><code> _activity_timeout_manager.TimeoutHandler += new Action(_weight_resolver.Cancel())l
try {
var weight = _weight_resolver.Resolve();
}
catch(CancelledOperationException) { .... }
</code></pre>
<p>where the activity manager is running a timer on tick of which it invokes events using TimeoutHandler.Invoke();</p>
<p>The problem is that even though it is properly registered with the event, Cancel() never gets called. I believe this is because the thread it is calling to is currently spinning and therefore it never gets a chance at the CPU.</p>
<p>What can I do to remedy the situation short of making the call to Resolve() asynchronous? It is extremely preferable for WeightResolver.Resolve() to stay synchronous because the code calling it should spin unless some return is provided anyways.</p>
<p><strong>EDIT:</strong> To clarify what I'm asking for. This seems like a fairly common set-up and I would be surprised if there isn't a simple standard way to handle it. I simply have never run across the situation before and don't know what exactly it could be.</p>
|
[
{
"answer_id": 230654,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 1,
"selected": false,
"text": "<p>This might not work for you, but based on the information you've provided, I'd suggest looking at thread.Join(XXX) where XXX is the number of milliseconds to wait. It'll greatly simplify your code.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/6b1kkss0.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/6b1kkss0.aspx</a></p>\n\n<p>you can block the calling thread to the new thread for a specified amount of time, after which you can abort the Resolve thread.</p>\n\n<pre><code>resolveThread.Start();\nresolveThread.Join(2000); //this will block the main thread, thus making resolve synchronous\nresolveThread.Abort(); //timeout has expired\n</code></pre>\n"
},
{
"answer_id": 230664,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 0,
"selected": false,
"text": "<p>Is this while loop ever giving up the CPU?</p>\n\n<pre><code>while(_source.CurrentWeight < threshold )\n</code></pre>\n\n<p>If not, then your inactivity timer won't get a chance to run. You might want to use ManualResetEvents (instead of the loop... have whatever sets _source.CurrentWeight set the event) or throw in a Thread.yield() every once in a while.</p>\n"
},
{
"answer_id": 230730,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 0,
"selected": false,
"text": "<p>What you need here are condition variables. I don't know specifically for .NET but in general you will have something like this</p>\n\n<pre><code>Condition cond;\nMutex lock;\n\npublic Cancel() {\n lock.lock()\n _cancelled = true;\n cond.signal(lock);\n lock.unlock();\n }\n public Weight Resolve(){\n _cancelled = false;\n lock.lock();\n while(_source.CurrentWeight < threshold) {\n if(_cancelled)\n {\n lock.unlock();\n throw new CancelledOperationException();\n }\n cond.timedWait(lock, 100);\n // Wait until one of the above conditions is met\n }\n lock.unlock();\n return _source.CurrentWeight\n }\n</code></pre>\n\n<p>even better would be if your WeightResolver signalled on the same condition when the weight changed. e.g.</p>\n\n<pre><code>Condition cond;\nMutex lock;\n\npublic Cancel() {\n lock.lock()\n _cancelled = true;\n cond.signal(lock);\n lock.unlock();\n }\n public Weight Resolve(){\n _cancelled = false;\n lock.lock();\n while(_source.CurrentWeight < threshold) {\n if(_cancelled)\n {\n lock.unlock();\n throw new CancelledOperationException();\n }\n cond.wait(lock);\n // Wait until one of the above conditions is met\n }\n lock.unlock();\n return _source.CurrentWeight\n }\n</code></pre>\n\n<p>and in the WeightMonitor Class, you had something like this.</p>\n\n<pre><code>public void updateWeight()\n{\n lock.lock();\n ...update weight;\n cond.signal(lock);\n lock.unlock();\n}\n</code></pre>\n\n<p>where the Conditionvariable and lock are the same. in both classes.</p>\n\n<p>This is a pretty standard use for condition variables, this is also how join is generally implemented.</p>\n"
},
{
"answer_id": 230733,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 0,
"selected": false,
"text": "<p>You should be using a <code>ManualResetEvent</code> instead of a <code>bool</code> for canceling.</p>\n\n<pre><code>class WeightResolver {\n WeightMonitor _source;\n ManualResetEvent _cancelled = new ManualResetEvent(false);\n Weight _threshold;\n\n public Cancel() {\n _cancelled.Set();\n }\n public Weight Resolve(){\n _cancelled = false;\n while(_source.CurrentWeight < threshold ) {\n if(_cancelled.WaitOne(100))\n throw new CancelledOperationException();\n // Wait until one of the above conditions is met\n }\n return _source.CurrentWeight\n }\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
I am trying to implement the following functionality:
```
class WeightResolver {
WeightMonitor _source;
bool _cancelled;
Weight _threshold;
public Cancel() {
_cancelled = true;
}
public Weight Resolve(){
_cancelled = false;
while(_source.CurrentWeight < threshold ) {
if(_cancelled)
throw new CancelledOperationException();
// Wait until one of the above conditions is met
}
return _source.CurrentWeight
}
}
```
However I am running into trouble managing my threads. For example, the Cancel method is registered via an event and Resolve invoked as follows:
```
_activity_timeout_manager.TimeoutHandler += new Action(_weight_resolver.Cancel())l
try {
var weight = _weight_resolver.Resolve();
}
catch(CancelledOperationException) { .... }
```
where the activity manager is running a timer on tick of which it invokes events using TimeoutHandler.Invoke();
The problem is that even though it is properly registered with the event, Cancel() never gets called. I believe this is because the thread it is calling to is currently spinning and therefore it never gets a chance at the CPU.
What can I do to remedy the situation short of making the call to Resolve() asynchronous? It is extremely preferable for WeightResolver.Resolve() to stay synchronous because the code calling it should spin unless some return is provided anyways.
**EDIT:** To clarify what I'm asking for. This seems like a fairly common set-up and I would be surprised if there isn't a simple standard way to handle it. I simply have never run across the situation before and don't know what exactly it could be.
|
This might not work for you, but based on the information you've provided, I'd suggest looking at thread.Join(XXX) where XXX is the number of milliseconds to wait. It'll greatly simplify your code.
<http://msdn.microsoft.com/en-us/library/6b1kkss0.aspx>
you can block the calling thread to the new thread for a specified amount of time, after which you can abort the Resolve thread.
```
resolveThread.Start();
resolveThread.Join(2000); //this will block the main thread, thus making resolve synchronous
resolveThread.Abort(); //timeout has expired
```
|
230,642 |
<p>On our live/production database I'm trying to add a trigger to a table, but have been unsuccessful. I have tried a few times, but it has taken more than 30 minutes for the create trigger statement to complete and I've cancelled it. </p>
<p>The table is one that gets read/written to often by a couple different processes. I have disabled the scheduled jobs that update the table and attempted at times when there is less activity on the table, but I'm not able to stop everything that accesses the table.</p>
<p>I do not believe there is a problem with the create trigger statement itself. The create trigger statement was successful and quick in a test environment, and the trigger works correctly when rows are inserted/updated to the table. Although when I created the trigger on the test database there was no load on the table and it had considerably less rows, which is different than on the live/production database (100 vs. 13,000,000+).</p>
<p>Here is the create trigger statement that I'm trying to run</p>
<pre><code>CREATE TRIGGER [OnItem_Updated]
ON [Item]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF update(State)
BEGIN
/* do some stuff including for each row updated call a stored
procedure that increments a value in table based on the
UserId of the updated row */
END
END
</code></pre>
<p>Can there be issues with creating a trigger on a table while rows are being updated or if it has many rows? </p>
<p>In SQLServer triggers are created enabled by default. Is it possible to create the trigger disabled by default? </p>
<p>Any other ideas?</p>
|
[
{
"answer_id": 230719,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 2,
"selected": false,
"text": "<p>That's odd. An <code>AFTER UPDATE</code> trigger shouldn't need to check existing rows in the table. I suppose it's possible that you aren't able to obtain a lock on the table to add the trigger.</p>\n\n<p>You might try creating a trigger that basically does nothing. If you can't create that, then it's a locking issue. If you can, then you could disable that trigger, add your intended code to the body, and enable it. (I do not believe you can disable a trigger during creation.)</p>\n"
},
{
"answer_id": 230723,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 2,
"selected": false,
"text": "<p>I believe the CREATE Trigger will attempt to put a lock on the entire table. </p>\n\n<p>If you have a lots of activity on that table it might have to wait a long time and you could be creating a deadlock.</p>\n\n<p>For any schema changes you should really get everyone of the database. </p>\n\n<p>That said it is tempting to put in \"small\" changes with active connections. You should take a look at the locks / connections to see where the lock contention is.</p>\n"
},
{
"answer_id": 231212,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 4,
"selected": true,
"text": "<p>The problem may not be in the table itself, but in the system tables that have to be updated in order to create the trigger. If you're doing any other kind of DDL as part of your normal processes they could be holding it up.</p>\n\n<p>Use sp_who to find out where the block is coming from then investigate from there.</p>\n"
},
{
"answer_id": 939616,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 2,
"selected": false,
"text": "<p>Part of the problem may also be the trigger itself. Could your trigger accidentally be updating all rows of the table? There is a big differnce between 100 rows in a test database and 13,000,000. It is a very bad idea to develop code against such a small set when you have such a large dataset as you can have no way to predict performance. SQL that works fine for 100 records can completely lock up a system with millions for hours. You really want to know that in dev, not when you promote to prod. </p>\n\n<p>Calling a stored proc in a trigger is usually a very bad choice. It also means that you have to loop through records which is an even worse choice in a trigger. Triggers must alawys account for multiple record inserts/updates or deletes. If someone inserts 100,000 rows (not unlikely if you have 13,000,000 records), then looping through a record based stored proc could take hours, lock the entire table and cause all users to want to hunt down the developer and kill (or at least maim) him because they cannot get their work done.</p>\n\n<p>I would not even consider putting this trigger on prod until you test against a record set simliar in size to prod.</p>\n\n<p>My friend Dennis wrote this article that illustrates why testing a small volumn of information when you have a large volumn of information can create difficulties on prd that you didn't notice on dev:\n<a href=\"http://blogs.lessthandot.com/index.php/DataMgmt/?blog=3&title=your-testbed-has-to-have-the-same-volume&disp=single&more=1&c=1&tb=1&pb=1#c1210\" rel=\"nofollow noreferrer\">http://blogs.lessthandot.com/index.php/DataMgmt/?blog=3&title=your-testbed-has-to-have-the-same-volume&disp=single&more=1&c=1&tb=1&pb=1#c1210</a></p>\n"
},
{
"answer_id": 37567052,
"author": "Marco Marsala",
"author_id": 2717254,
"author_profile": "https://Stackoverflow.com/users/2717254",
"pm_score": 0,
"selected": false,
"text": "<p>Run <code>DISABLE TRIGGER triggername ON tablename</code> before altering the trigger, then reenable it with <code>ENABLE TRIGGER triggername ON tablename</code></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21353/"
] |
On our live/production database I'm trying to add a trigger to a table, but have been unsuccessful. I have tried a few times, but it has taken more than 30 minutes for the create trigger statement to complete and I've cancelled it.
The table is one that gets read/written to often by a couple different processes. I have disabled the scheduled jobs that update the table and attempted at times when there is less activity on the table, but I'm not able to stop everything that accesses the table.
I do not believe there is a problem with the create trigger statement itself. The create trigger statement was successful and quick in a test environment, and the trigger works correctly when rows are inserted/updated to the table. Although when I created the trigger on the test database there was no load on the table and it had considerably less rows, which is different than on the live/production database (100 vs. 13,000,000+).
Here is the create trigger statement that I'm trying to run
```
CREATE TRIGGER [OnItem_Updated]
ON [Item]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF update(State)
BEGIN
/* do some stuff including for each row updated call a stored
procedure that increments a value in table based on the
UserId of the updated row */
END
END
```
Can there be issues with creating a trigger on a table while rows are being updated or if it has many rows?
In SQLServer triggers are created enabled by default. Is it possible to create the trigger disabled by default?
Any other ideas?
|
The problem may not be in the table itself, but in the system tables that have to be updated in order to create the trigger. If you're doing any other kind of DDL as part of your normal processes they could be holding it up.
Use sp\_who to find out where the block is coming from then investigate from there.
|
230,643 |
<p>Is there any elegant way in the Android API for detecting new media when it is written to the device? I’m mainly interested in photos taken by the camera, video taken by the camera and audio recorded from the mic.</p>
<p>My current thinking is to periodically scan each media content provider and filter based on last scan time.</p>
<p>I’m just wondering if there is some service I can get realtime notifications.</p>
|
[
{
"answer_id": 232115,
"author": "Declan Shanaghy",
"author_id": 21297,
"author_profile": "https://Stackoverflow.com/users/21297",
"pm_score": 2,
"selected": false,
"text": "<p>Aha!</p>\n\n<p>A <a href=\"http://code.google.com/android/reference/android/database/ContentObserver.html\" rel=\"nofollow noreferrer\">content observer</a> is what i need!</p>\n\n<p><a href=\"http://mylifewithandroid.blogspot.com/2008/03/observing-content.html\" rel=\"nofollow noreferrer\">Here's where i found out about it</a></p>\n"
},
{
"answer_id": 236756,
"author": "Reto Meier",
"author_id": 822,
"author_profile": "https://Stackoverflow.com/users/822",
"pm_score": 3,
"selected": false,
"text": "<p>There's a special broadcast Intent that should get called every time an application writes anything new to the Media Store:</p>\n\n<pre><code>Intent.ACTION_MEDIA_SCANNER_SCAN_FILE\n</code></pre>\n\n<p>The Broadcast Intent includes the path to the new file, accessible through the <code>Intent.getDataString()</code> method.</p>\n\n<p>To listen for it, just create a <code>BroadcastReceiver</code> and register it using an <code>IntentFilter</code> as shown below:</p>\n\n<pre><code>registerReceiver(new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n String newFileURL = intent.getDataString();\n // TODO React to new Media here. \n } \n }, new IntentFilter(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));\n</code></pre>\n\n<p>This will only work for files being inserted into one of the Media Store Content Providers. Also, it depends on the application that's putting it there broadcasting the intent, which all the native (Google) application do.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21297/"
] |
Is there any elegant way in the Android API for detecting new media when it is written to the device? I’m mainly interested in photos taken by the camera, video taken by the camera and audio recorded from the mic.
My current thinking is to periodically scan each media content provider and filter based on last scan time.
I’m just wondering if there is some service I can get realtime notifications.
|
There's a special broadcast Intent that should get called every time an application writes anything new to the Media Store:
```
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE
```
The Broadcast Intent includes the path to the new file, accessible through the `Intent.getDataString()` method.
To listen for it, just create a `BroadcastReceiver` and register it using an `IntentFilter` as shown below:
```
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newFileURL = intent.getDataString();
// TODO React to new Media here.
}
}, new IntentFilter(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
```
This will only work for files being inserted into one of the Media Store Content Providers. Also, it depends on the application that's putting it there broadcasting the intent, which all the native (Google) application do.
|
230,644 |
<p>I've got a tomcat instance with several apps running on it... I want the root of my new domain to go to one of these apps (context path of blah).. so I have the following set up:</p>
<pre><code><Location />
ProxyPass ajp://localhost:8025/blah
ProxyPassReverse ajp://localhost:8025/blah
</Location>
</code></pre>
<p>it kinda works... going to mydomain.com/index.jsp works except the app still thinks it needs to add the /blah/ to everything like css and js.. is there something I can do without deploying the app to ROOT or changing the tomcat server config? I'd like to keep all this kind of thing on the apache side, if it's possible.</p>
<p>I'm thinking I may not be understanding the proxypassreverse directive.. </p>
|
[
{
"answer_id": 231723,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 0,
"selected": false,
"text": "<p>it looks like this is kind of a <a href=\"http://dltj.org/article/apache-httpd-and-tomcat/\" rel=\"nofollow noreferrer\">pain in the rear</a>.</p>\n\n<p>apache is literally rewriting pages as it serves them... </p>\n\n<p>I think I'll go a different route.</p>\n"
},
{
"answer_id": 237697,
"author": "f4nt",
"author_id": 14838,
"author_profile": "https://Stackoverflow.com/users/14838",
"pm_score": 3,
"selected": true,
"text": "<p>If you're wanting to server the app the /, Tomcat expects the app to be mounted at /, and have the name of ROOT. At least that's how I've always handled the situation personally. Even if you just symlink the app into ROOT, that should mitigate your problems. If you have an app placed in ${tomcat_home}/webapps/newapp, then Tomcat deploys it with a context of /newapp. At least, that's been the case in my history. Also, not sure if it matters but I've always used:</p>\n\n<pre><code>ProxyPass / ajp://localhost:8025/blah\nProxyPassReverse / ajp://localhost:8025/blah\n</code></pre>\n"
},
{
"answer_id": 707544,
"author": "Matt Woodward",
"author_id": 3612,
"author_profile": "https://Stackoverflow.com/users/3612",
"pm_score": 0,
"selected": false,
"text": "<p>If you configure hosts on the Tomcat side as well then you can proxy to them and eliminate the context path for non-root webapps--in Tomcat server.xml:</p>\n\n<pre><code><Host name=\"myhost\">\n <Context path=\"\" docBase=\"/path/to/files\" />\n</Host>\n</code></pre>\n\n<p>And on the Apache side:</p>\n\n<pre><code><VirtualHost *:80>\n ServerName myhost\n ProxyPass / ajp://myhost:8009/\n ProxyPassReverse / ajp://myhost:8009/\n</VirtualHost>\n</code></pre>\n\n<p>Hope that helps.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031/"
] |
I've got a tomcat instance with several apps running on it... I want the root of my new domain to go to one of these apps (context path of blah).. so I have the following set up:
```
<Location />
ProxyPass ajp://localhost:8025/blah
ProxyPassReverse ajp://localhost:8025/blah
</Location>
```
it kinda works... going to mydomain.com/index.jsp works except the app still thinks it needs to add the /blah/ to everything like css and js.. is there something I can do without deploying the app to ROOT or changing the tomcat server config? I'd like to keep all this kind of thing on the apache side, if it's possible.
I'm thinking I may not be understanding the proxypassreverse directive..
|
If you're wanting to server the app the /, Tomcat expects the app to be mounted at /, and have the name of ROOT. At least that's how I've always handled the situation personally. Even if you just symlink the app into ROOT, that should mitigate your problems. If you have an app placed in ${tomcat\_home}/webapps/newapp, then Tomcat deploys it with a context of /newapp. At least, that's been the case in my history. Also, not sure if it matters but I've always used:
```
ProxyPass / ajp://localhost:8025/blah
ProxyPassReverse / ajp://localhost:8025/blah
```
|
230,649 |
<h2>Question</h2>
<p>I'm looking for a Java in-memory object caching API. Any recommendations? What solutions have you used in the past?</p>
<h2>Current</h2>
<p>Right now, I'm just using a Map:</p>
<pre><code>Map cache = new HashMap<String, Object>();
cache.put("key", value);
</code></pre>
<h2>Requirements</h2>
<p>I need to extend the cache to include basic features like:</p>
<ul>
<li>Max size</li>
<li>Time to live</li>
</ul>
<p>However, I don't need more sophisticated features like:</p>
<ul>
<li>Access from multiple processes (caching server)</li>
<li>Persistence (to disk)</li>
</ul>
<h2>Suggestions</h2>
<p>In-Memory caching:</p>
<ul>
<li><a href="http://guava-libraries.googlecode.com" rel="noreferrer">Guava</a> CacheBuilder - active development. See this <a href="https://github.com/liubo404/it-ebooks/blob/master/pdf/JavaCachingwithGuava.pdf" rel="noreferrer">presentation</a>.</li>
<li><a href="http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LRUMap.html" rel="noreferrer">LRUMap</a> - Config via API. No TTL. Not purpose built for caching.</li>
<li><a href="http://whirlycache.dev.java.net/" rel="noreferrer">whirlycache</a> - XML config. Mailing list. Last updated 2006.</li>
<li><a href="http://cache4j.sourceforge.net/" rel="noreferrer">cache4j</a> - XML config. Documentation in Russian. Last updated 2006.</li>
</ul>
<p>Enterprise caching:</p>
<ul>
<li><a href="http://jakarta.apache.org/jcs" rel="noreferrer">JCS</a> - Properties config. Extensive documentation.</li>
<li><a href="http://ehcache.sourceforge.net" rel="noreferrer">Ehcache</a> - XML config. Extensive documentation. By far the most popular according to Google hits.</li>
</ul>
|
[
{
"answer_id": 230659,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"http://ehcache.sourceforge.net/\" rel=\"noreferrer\">EHCache</a> is very nice. You can create an in memory cache. Check out their <a href=\"http://ehcache.sourceforge.net/documentation/samples.html\" rel=\"noreferrer\">code samples</a> for an example of creating an in memory cache. You can specify a max size, and a time to live.</p>\n\n<p>EHCache does offer some advanced features, but if your not interested in using them - don't. But it's nice to know they are there if your requirements ever change.</p>\n\n<p>Here is an in memory cache. Created in code, with no configuration files.</p>\n\n<pre><code>CacheManager cacheManager = CacheManager.getInstance();\nint oneDay = 24 * 60 * 60;\nCache memoryOnlyCache = new Cache(\"name\", 200, false, false, oneDay, oneDay);\ncacheManager.addCache(memoryOnlyCache);\n</code></pre>\n\n<p>Creates a cache that will hold 200 elements, and has a ttl of 24 hours.</p>\n"
},
{
"answer_id": 230671,
"author": "Ichorus",
"author_id": 27247,
"author_profile": "https://Stackoverflow.com/users/27247",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://jakarta.apache.org/jcs/\" rel=\"noreferrer\">JCS</a> is tried and true. Even though it is light as far as caching mechanisms go, you might dig into the actual code and mimic what they do with HashMap under the covers to exactly what you need and no more. You seem to have a pretty good idea of what you are looking for. </p>\n"
},
{
"answer_id": 230727,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 3,
"selected": false,
"text": "<p>You can check out LinkedHashMap to implement a simple cache without third party jars:</p>\n\n<pre><code> Map <String, Foo> cache = new LinkedHashMap<String, Foo>(MAX_ENTRIES + 1, .75F, true) {\n\n public boolean removeEldestEntry(Map.Entry<String, Foo> eldest) {\n return size() > MAX_ENTRIES;\n }\n };\n</code></pre>\n\n<p>then you can get from the cache like</p>\n\n<pre><code> Foo foo = cache.get(key);\n if (foo == null && !cache.containsKey(key)) {\n try {\n FooDAO fooDAO = DAOFactory.getFooDAO(conn);\n foo = fooDAO.getFooByKey(key);\n cache.put(key, foo);\n } catch (SQLException sqle) {\n logger.error(\"[getFoo] SQL Exception when accessing Foo\", sqle);\n }\n }\n</code></pre>\n\n<p>rest left as exercise for reader :)</p>\n"
},
{
"answer_id": 1220547,
"author": "Travis Reeder",
"author_id": 105562,
"author_profile": "https://Stackoverflow.com/users/105562",
"pm_score": 3,
"selected": false,
"text": "<p>You can also check out my little cache library called KittyCache at: </p>\n\n<p><a href=\"https://github.com/treeder/kitty-cache\" rel=\"nofollow noreferrer\">https://github.com/treeder/kitty-cache</a></p>\n\n<p>There are some performance benchmarks vs ehcache.</p>\n\n<p>It's used in the <a href=\"http://code.google.com/p/simplejpa/\" rel=\"nofollow noreferrer\">SimpleJPA</a> project as a second level cache.</p>\n"
},
{
"answer_id": 1367663,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 6,
"selected": false,
"text": "<p>I really like the <a href=\"https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/MapMaker.html\" rel=\"nofollow noreferrer\"><code>MapMaker</code></a> that comes with <a href=\"https://github.com/google/guava\" rel=\"nofollow noreferrer\">Google Guava</a> (<a href=\"https://google.github.io/guava/releases/snapshot/api/docs/\" rel=\"nofollow noreferrer\">API</a>)</p>\n\n<p>The JavaDoc has a pretty neat example that demonstrates both its ease of use and its power:</p>\n\n<pre><code>ConcurrentMap<Key, Graph> graphs = new MapMaker()\n .concurrencyLevel(32)\n .softKeys()\n .weakValues()\n .expiration(30, TimeUnit.MINUTES)\n .makeComputingMap(\n new Function<Key, Graph>() {\n public Graph apply(Key key) {\n return createExpensiveGraph(key);\n }\n });\n</code></pre>\n\n<p>Furthermore, release 10.0 of Guava introduced the much more extensive <a href=\"https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/cache/package-summary.html\" rel=\"nofollow noreferrer\"><code>com.google.common.cache</code> package</a> (there's a <a href=\"https://github.com/google/guava/wiki/CachesExplained\" rel=\"nofollow noreferrer\">nice wiki entry on how to use them</a>).</p>\n"
},
{
"answer_id": 1368395,
"author": "Zorkus",
"author_id": 1965110,
"author_profile": "https://Stackoverflow.com/users/1965110",
"pm_score": 2,
"selected": false,
"text": "<p>memcached has client for Java. <a href=\"http://www.danga.com/memcached/\" rel=\"nofollow noreferrer\">http://www.danga.com/memcached/</a> Requires separate process to be a caching server, but powerful thing.</p>\n"
},
{
"answer_id": 7314960,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 3,
"selected": false,
"text": "<p>Guava's <a href=\"https://google.github.io/guava/releases/18.0/api/docs/com/google/common/collect/MapMaker.html\" rel=\"nofollow noreferrer\">MapMaker</a> has been replaced by their <a href=\"https://google.github.io/guava/releases/21.0/api/docs/com/google/common/cache/CacheBuilder.html\" rel=\"nofollow noreferrer\">CacheBuilder</a> class.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7679/"
] |
Question
--------
I'm looking for a Java in-memory object caching API. Any recommendations? What solutions have you used in the past?
Current
-------
Right now, I'm just using a Map:
```
Map cache = new HashMap<String, Object>();
cache.put("key", value);
```
Requirements
------------
I need to extend the cache to include basic features like:
* Max size
* Time to live
However, I don't need more sophisticated features like:
* Access from multiple processes (caching server)
* Persistence (to disk)
Suggestions
-----------
In-Memory caching:
* [Guava](http://guava-libraries.googlecode.com) CacheBuilder - active development. See this [presentation](https://github.com/liubo404/it-ebooks/blob/master/pdf/JavaCachingwithGuava.pdf).
* [LRUMap](http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LRUMap.html) - Config via API. No TTL. Not purpose built for caching.
* [whirlycache](http://whirlycache.dev.java.net/) - XML config. Mailing list. Last updated 2006.
* [cache4j](http://cache4j.sourceforge.net/) - XML config. Documentation in Russian. Last updated 2006.
Enterprise caching:
* [JCS](http://jakarta.apache.org/jcs) - Properties config. Extensive documentation.
* [Ehcache](http://ehcache.sourceforge.net) - XML config. Extensive documentation. By far the most popular according to Google hits.
|
[EHCache](http://ehcache.sourceforge.net/) is very nice. You can create an in memory cache. Check out their [code samples](http://ehcache.sourceforge.net/documentation/samples.html) for an example of creating an in memory cache. You can specify a max size, and a time to live.
EHCache does offer some advanced features, but if your not interested in using them - don't. But it's nice to know they are there if your requirements ever change.
Here is an in memory cache. Created in code, with no configuration files.
```
CacheManager cacheManager = CacheManager.getInstance();
int oneDay = 24 * 60 * 60;
Cache memoryOnlyCache = new Cache("name", 200, false, false, oneDay, oneDay);
cacheManager.addCache(memoryOnlyCache);
```
Creates a cache that will hold 200 elements, and has a ttl of 24 hours.
|
230,662 |
<p>I have a table that has a column with a default value:</p>
<pre><code>create table t (
value varchar(50) default ('something')
)
</code></pre>
<p>I'm using a stored procedure to insert values into this table:</p>
<pre><code>create procedure t_insert (
@value varchar(50) = null
)
as
insert into t (value) values (@value)
</code></pre>
<p>The question is, how do I get it to use the default when <code>@value</code> is <code>null</code>? I tried:</p>
<pre><code>insert into t (value) values ( isnull(@value, default) )
</code></pre>
<p>That obviously didn't work. Also tried a <code>case</code> statement, but that didn't fair well either. Any other suggestions? Am I going about this the wrong way?</p>
<p>Update: I'm trying to accomplish this <strong>without</strong> having to:</p>
<ol>
<li>maintain the <code>default</code> value in multiple places, and</li>
<li>use multiple <code>insert</code> statements.</li>
</ol>
<p>If this isn't possible, well I guess I'll just have to live with it. It just seems that something this should be attainable.</p>
<p>Note: my actual table has more than one column. I was just quickly writing an example.</p>
|
[
{
"answer_id": 230676,
"author": "Brian Hasden",
"author_id": 28926,
"author_profile": "https://Stackoverflow.com/users/28926",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I know, the default value is only inserted when you don't specify a value in the insert statement. So, for example, you'd need to do something like the following in a table with three fields (value2 being defaulted)</p>\n\n<pre><code>INSERT INTO t (value1, value3) VALUES ('value1', 'value3')\n</code></pre>\n\n<p>And then value2 would be defaulted. Maybe someone will chime in on how to accomplish this for a table with a single field.</p>\n"
},
{
"answer_id": 230678,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 1,
"selected": false,
"text": "<p>You can use default values for the parameters of stored procedures:</p>\n\n<pre><code>CREATE PROCEDURE MyTestProcedure ( @MyParam1 INT,\n@MyParam2 VARCHAR(20) = ‘ABC’,\n@MyParam3 INT = NULL)\nAS\nBEGIN\n -- Procedure body here\n\nEND\n</code></pre>\n\n<p>If @MyParam2 is not supplied, it will have the 'ABC' value...</p>\n"
},
{
"answer_id": 230681,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "<p>Don't specify the column or value when inserting and the DEFAULT constaint's value will be substituted for the missing value.</p>\n\n<p>I don't know how this would work in a single column table. I mean: it would, but it wouldn't be very useful.</p>\n"
},
{
"answer_id": 230717,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": -1,
"selected": false,
"text": "<p>The easiest way to do this is to modify the table declaration to be </p>\n\n<pre><code>CREATE TABLE Demo\n(\n MyColumn VARCHAR(10) NOT NULL DEFAULT 'Me'\n)\n</code></pre>\n\n<p>Now, in your stored procedure you can do something like.</p>\n\n<pre><code>CREATE PROCEDURE InsertDemo\n @MyColumn VARCHAR(10) = null\nAS\nINSERT INTO Demo (MyColumn) VALUES(@MyColumn)\n</code></pre>\n\n<p>However, this method ONLY works if you can't have a null, otherwise, your stored procedure would have to use a different form of insert to trigger a default.</p>\n"
},
{
"answer_id": 230771,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 4,
"selected": false,
"text": "<p>Try an if statement ... </p>\n\n<pre><code>if @value is null \n insert into t (value) values (default)\nelse\n insert into t (value) values (@value)\n</code></pre>\n"
},
{
"answer_id": 230902,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 4,
"selected": false,
"text": "<p>Christophe, </p>\n\n<p>The default value on a column is only applied if you don't specify the column in the INSERT statement.</p>\n\n<p>Since you're explicitiy listing the column in your insert statement, and explicity setting it to NULL, that's overriding the default value for that column</p>\n\n<p>What you need to do is \"if a null is passed into your sproc then don't attempt to insert for that column\".</p>\n\n<p>This is a quick and nasty example of how to do that with some dynamic sql.</p>\n\n<p>Create a table with some columns with default values...</p>\n\n<pre><code>CREATE TABLE myTable (\n always VARCHAR(50),\n value1 VARCHAR(50) DEFAULT ('defaultcol1'),\n value2 VARCHAR(50) DEFAULT ('defaultcol2'),\n value3 VARCHAR(50) DEFAULT ('defaultcol3')\n)\n</code></pre>\n\n<p>Create a SPROC that dynamically builds and executes your insert statement based on input params</p>\n\n<pre><code>ALTER PROCEDURE t_insert (\n @always VARCHAR(50),\n @value1 VARCHAR(50) = NULL,\n @value2 VARCHAR(50) = NULL,\n @value3 VARCAHR(50) = NULL\n)\nAS \nBEGIN\nDECLARE @insertpart VARCHAR(500)\nDECLARE @valuepart VARCHAR(500)\n\nSET @insertpart = 'INSERT INTO myTable ('\nSET @valuepart = 'VALUES ('\n\n IF @value1 IS NOT NULL\n BEGIN\n SET @insertpart = @insertpart + 'value1,'\n SET @valuepart = @valuepart + '''' + @value1 + ''', '\n END\n\n IF @value2 IS NOT NULL\n BEGIN\n SET @insertpart = @insertpart + 'value2,'\n SET @valuepart = @valuepart + '''' + @value2 + ''', '\n END\n\n IF @value3 IS NOT NULL\n BEGIN\n SET @insertpart = @insertpart + 'value3,'\n SET @valuepart = @valuepart + '''' + @value3 + ''', '\n END\n\n SET @insertpart = @insertpart + 'always) '\n SET @valuepart = @valuepart + + '''' + @always + ''')'\n\n--print @insertpart + @valuepart\nEXEC (@insertpart + @valuepart)\nEND\n</code></pre>\n\n<p>The following 2 commands should give you an example of what you want as your outputs...</p>\n\n<pre><code>EXEC t_insert 'alwaysvalue'\nSELECT * FROM myTable\n\nEXEC t_insert 'alwaysvalue', 'val1'\nSELECT * FROM myTable\n\nEXEC t_insert 'alwaysvalue', 'val1', 'val2', 'val3'\nSELECT * FROM myTable\n</code></pre>\n\n<p>I know this is a very convoluted way of doing what you need to do.\nYou could probably equally select the default value from the InformationSchema for the relevant columns but to be honest, I might consider just adding the default value to param at the top of the procedure</p>\n"
},
{
"answer_id": 231382,
"author": "Richard T",
"author_id": 26976,
"author_profile": "https://Stackoverflow.com/users/26976",
"pm_score": -1,
"selected": false,
"text": "<p>The questioner needs to learn the difference between an empty value provided and null.</p>\n\n<p>Others have posted the right basic answer: A provided value, including a null, is <em>something</em> and therefore it's used. Default ONLY provides a value when none is provided. But the real problem here is lack of understanding of the value of null.</p>\n\n<p>.</p>\n"
},
{
"answer_id": 231609,
"author": "Paul Osterhout",
"author_id": 30976,
"author_profile": "https://Stackoverflow.com/users/30976",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the COALESCE function in MS SQL.</p>\n\n<p>INSERT INTO t ( value ) VALUES( COALESCE(@value, 'something') )</p>\n\n<p>Personally, I'm not crazy about this solution as it is a maintenance nightmare if you want to change the default value.</p>\n\n<p>My preference would be Mitchel Sellers proposal, but that doesn't work in MS SQL. Can't speak to other SQL dbms.</p>\n"
},
{
"answer_id": 231822,
"author": "Lurker Indeed",
"author_id": 16951,
"author_profile": "https://Stackoverflow.com/users/16951",
"pm_score": 2,
"selected": false,
"text": "<p>Probably not the most performance friendly way, but you could create a scalar function that pulls from the information schema with the table and column name, and then call that using the isnull logic you tried earlier:</p>\n\n<pre><code> CREATE FUNCTION GetDefaultValue\n (\n @TableName VARCHAR(200),\n @ColumnName VARCHAR(200)\n )\n RETURNS VARCHAR(200)\n AS\n BEGIN\n -- you'd probably want to have different functions for different data types if\n -- you go this route\n RETURN (SELECT TOP 1 REPLACE(REPLACE(REPLACE(COLUMN_DEFAULT, '(', ''), ')', ''), '''', '') \n FROM information_schema.columns\n WHERE table_name = @TableName AND column_name = @ColumnName)\n\n END\n GO\n</code></pre>\n\n<p>And then call it like this:</p>\n\n<pre><code>INSERT INTO t (value) VALUES ( ISNULL(@value, SELECT dbo.GetDefaultValue('t', 'value') )\n</code></pre>\n"
},
{
"answer_id": 9361365,
"author": "sihirbazzz",
"author_id": 967770,
"author_profile": "https://Stackoverflow.com/users/967770",
"pm_score": 0,
"selected": false,
"text": "<p>Hope To help to -newbie as i am- Ones who uses Upsert statements in MSSQL.. (This code i used in my project on MSSQL 2008 R2 and works simply perfect..May be It's not Best Practise.. Execution time statistics shows execution time as 15 milliSeconds with insert statement) </p>\n\n<p>Just set your column's \"Default value or binding\" field as what you decide to use as default value for your column and Also set the column as Not accept null values from design menu and create this stored Proc..</p>\n\n<pre><code>`USE [YourTable]\nGO\n\n\nSET ANSI_NULLS ON\nGO\n\nSET QUOTED_IDENTIFIER ON\nGO\n\nCREATE PROC [dbo].[YourTableName]\n\n @Value smallint,\n @Value1 bigint,\n @Value2 varchar(50),\n @Value3 varchar(20),\n @Value4 varchar(20),\n @Value5 date,\n @Value6 varchar(50),\n @Value7 tinyint,\n @Value8 tinyint,\n @Value9 varchar(20),\n @Value10 varchar(20),\n @Value11 varchar(250),\n @Value12 tinyint,\n @Value13 varbinary(max) \n</code></pre>\n\n<p>-- in my project @Value13 is a photo column which storing as byte array..\n--And i planned to use a default photo when there is no photo passed \n--to sp to store in db.. </p>\n\n<pre><code>AS\n--SET NOCOUNT ON\nIF @Value = 0 BEGIN\n INSERT INTO YourTableName (\n [TableColumn1],\n [TableColumn2],\n [TableColumn3],\n [TableColumn4],\n [TableColumn5],\n [TableColumn6],\n [TableColumn7],\n [TableColumn8],\n [TableColumn9],\n [TableColumn10],\n [TableColumn11],\n [TableColumn12],\n [TableColumn13]\n )\n VALUES (\n @Value1,\n @Value2,\n @Value3,\n @Value4,\n @Value5,\n @Value6,\n @Value7,\n @Value8,\n @Value9,\n @Value10,\n @Value11,\n @Value12,\n default\n )\n SELECT SCOPE_IDENTITY() As InsertedID\nEND\nELSE BEGIN\n UPDATE YourTableName SET \n [TableColumn1] = @Value1,\n [TableColumn2] = @Value2,\n [TableColumn3] = @Value3,\n [TableColumn4] = @Value4,\n [TableColumn5] = @Value5,\n [TableColumn6] = @Value6,\n [TableColumn7] = @Value7,\n [TableColumn8] = @Value8,\n [TableColumn9] = @Value9,\n [TableColumn10] = @Value10,\n [TableColumn11] = @Value11,\n [TableColumn12] = @Value12,\n [TableColumn13] = @Value13\n WHERE [TableColumn] = @Value\n\nEND\nGO`\n</code></pre>\n"
},
{
"answer_id": 10322923,
"author": "sqlserverguy",
"author_id": 1357127,
"author_profile": "https://Stackoverflow.com/users/1357127",
"pm_score": 2,
"selected": false,
"text": "<p>This is the best I can come up with. It prevents sql injection uses only one insert statement and can ge extended with more case statements.</p>\n\n<pre><code>CREATE PROCEDURE t_insert ( @value varchar(50) = null )\nas\nDECLARE @sQuery NVARCHAR (MAX);\nSET @sQuery = N'\ninsert into __t (value) values ( '+\nCASE WHEN @value IS NULL THEN ' default ' ELSE ' @value ' END +' );';\n\nEXEC sp_executesql \n@stmt = @sQuery, \n@params = N'@value varchar(50)',\n@value = @value;\n\nGO\n</code></pre>\n"
},
{
"answer_id": 10831236,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 0,
"selected": false,
"text": "<p>With enough defaults on a table, you can simply say:</p>\n\n<pre><code>INSERT t DEFAULT VALUES\n</code></pre>\n\n<p>Note that this is quite an unlikely case, however. </p>\n\n<p>I've only had to use it once in a production environment. We had two closely related tables, and needed to guarantee that neither table had the same UniqueID, so we had a separate table which just had an identity column, and the best way to insert into it was with the syntax above.</p>\n"
},
{
"answer_id": 25590863,
"author": "Nicolás Orlando",
"author_id": 3994419,
"author_profile": "https://Stackoverflow.com/users/3994419",
"pm_score": 2,
"selected": false,
"text": "<p>chrisofspades, </p>\n\n<p>As far as I know that behavior is not compatible with the way the db engine works, \nbut there is a simple (i don't know if elegant, but performant) solution to achive your two objectives of <strong>DO NOT</strong></p>\n\n<ol>\n<li>maintain the default value in multiple places, and </li>\n<li>use multiple insert statements.</li>\n</ol>\n\n<p>The solution is to use two fields, one nullable for insert, and other one calculated to selections:</p>\n\n<pre><code>CREATE TABLE t (\n insValue VARCHAR(50) NULL\n , selValue AS ISNULL(insValue, 'something')\n)\n\nDECLARE @d VARCHAR(10)\nINSERT INTO t (insValue) VALUES (@d) -- null\nSELECT selValue FROM t\n</code></pre>\n\n<p>This method even let You centralize the management of business defaults in a parameter table, placing an ad hoc function to do this, vg changing: </p>\n\n<pre><code>selValue AS ISNULL(insValue, 'something')\n</code></pre>\n\n<p>for</p>\n\n<pre><code>selValue AS ISNULL(insValue, **getDef(t,1)**)\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 35613752,
"author": "Roy Fulbright",
"author_id": 975435,
"author_profile": "https://Stackoverflow.com/users/975435",
"pm_score": -1,
"selected": false,
"text": "<p>The most succinct solution I could come up with is to follow the insert with an update for the column with the default:</p>\n\n<pre><code>IF OBJECT_ID('tempdb..#mytest') IS NOT NULL DROP TABLE #mytest\nCREATE TABLE #mytest(f1 INT DEFAULT(1), f2 INT)\nINSERT INTO #mytest(f1,f2) VALUES (NULL,2)\nINSERT INTO #mytest(f1,f2) VALUES (3,3)\n\nUPDATE #mytest SET f1 = DEFAULT WHERE f1 IS NULL\n\nSELECT * FROM #mytest\n</code></pre>\n"
},
{
"answer_id": 43410866,
"author": "Blade",
"author_id": 3384036,
"author_profile": "https://Stackoverflow.com/users/3384036",
"pm_score": 2,
"selected": false,
"text": "<p>The best option by far is to create an INSTEAD OF INSERT trigger for your table, removing the default values from your table, and moving them into the trigger.</p>\n\n<p>This will look like the following:</p>\n\n<pre><code>create trigger dbo.OnInsertIntoT\nON TablenameT\nINSTEAD OF INSERT\nAS\ninsert into TablenameT\nselect\n IsNull(column1 ,<default_value>)\n ,IsNull(column2 ,<default_value>)\n ...\nfrom inserted\n</code></pre>\n\n<p>This makes it work NO MATTER what code tries to insert NULLs into your table, avoids stored procedures, is completely transparent, and you only need to maintain your default values in one place, namely this trigger.</p>\n"
},
{
"answer_id": 52522020,
"author": "Allinuon",
"author_id": 10419896,
"author_profile": "https://Stackoverflow.com/users/10419896",
"pm_score": -1,
"selected": false,
"text": "<p>The pattern I generally use is to create the row without the columns that have default constraints, then update the columns to replace the default values with supplied values (if not null).</p>\n\n<p>Assuming col1 is the primary key and col4 and col5 have a default contraint</p>\n\n<pre><code>-- create initial row with default values\ninsert table1 (col1, col2, col3)\n values (@col1, @col2, @col3)\n\n-- update default values, if supplied\nupdate table1\n set col4 = isnull(@col4, col4),\n col5 = isnull(@col5, col5)\n where col1 = @col1\n</code></pre>\n\n<p>If you want the actual values defaulted into the table ...</p>\n\n<pre><code>-- create initial row with default values\ninsert table1 (col1, col2, col3)\n values (@col1, @col2, @col3)\n\n-- create a container to hold the values actually inserted into the table\ndeclare @inserted table (col4 datetime, col5 varchar(50))\n\n-- update default values, if supplied\nupdate table1\n set col4 = isnull(@col4, col4),\n col5 = isnull(@col5, col5)\n output inserted.col4, inserted.col5 into @inserted (col4, col5)\n where col1 = @col1\n\n-- get the values defaulted into the table (optional)\nselect @col4 = col4, @col5 = col5 from @inserted\n</code></pre>\n\n<p>Cheers...</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2614/"
] |
I have a table that has a column with a default value:
```
create table t (
value varchar(50) default ('something')
)
```
I'm using a stored procedure to insert values into this table:
```
create procedure t_insert (
@value varchar(50) = null
)
as
insert into t (value) values (@value)
```
The question is, how do I get it to use the default when `@value` is `null`? I tried:
```
insert into t (value) values ( isnull(@value, default) )
```
That obviously didn't work. Also tried a `case` statement, but that didn't fair well either. Any other suggestions? Am I going about this the wrong way?
Update: I'm trying to accomplish this **without** having to:
1. maintain the `default` value in multiple places, and
2. use multiple `insert` statements.
If this isn't possible, well I guess I'll just have to live with it. It just seems that something this should be attainable.
Note: my actual table has more than one column. I was just quickly writing an example.
|
Try an if statement ...
```
if @value is null
insert into t (value) values (default)
else
insert into t (value) values (@value)
```
|
230,687 |
<p>PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not.</p>
<p>Can we build similar feature for C/C++ (some kind of symbol table lookup)?</p>
|
[
{
"answer_id": 230700,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>Not really. You can't dynamically create variables (though you can dynamically create storage with malloc() et al, or new et al. in C++) in C. I suppose dynamically loaded libraries blur the picture, but even there, the way you establish whether the variable exists is by looking up its name. If the name is not there, then, short of running a compiler to create a dynamically loaded module and then loading it, you are probably stuck. The concept really doesn't apply to C or C++.</p>\n"
},
{
"answer_id": 230729,
"author": "Jeffrey Martinez",
"author_id": 29703,
"author_profile": "https://Stackoverflow.com/users/29703",
"pm_score": 5,
"selected": true,
"text": "<p>I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe).</p>\n\n<p>You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously explicitly defined. There really is no such thing as an \"unset\" variable in C++.</p>\n\n<p>Even if you say \"int var;\" and do not initialize it, the variable has a value, usually garbage, but it's still \"set\" in the PHP sense.</p>\n\n<p>The closes I suppose would be the preprocessor's #ifdef and #ifndef which only checks to see if you've defined a variable using #define. But in my experience this is mostly used for omitting or adding code based on flags. For example:</p>\n\n<pre><code>// code code code\n#ifdef DEBUG\n// debug only code that will not be included in final product.\n#endif\n// more code more code\n</code></pre>\n\n<p>You can define DEBUG using #define to determine whether to include \"DEBUG\" code now.</p>\n\n<p>Perhaps telling a bit more about what you're trying to do with the C++ equivalent of isset will give you a better idea of how to go about doing it \"The C++ Way\".</p>\n"
},
{
"answer_id": 230816,
"author": "Jon Trauntvein",
"author_id": 19674,
"author_profile": "https://Stackoverflow.com/users/19674",
"pm_score": 3,
"selected": false,
"text": "<p>There is no direct means of doing this in the language. However, it is possible to do this sort of thing by using a map such as the following:</p>\n\n<pre><code>typedef std::map<std::string, int> variables_type;\nvariables_type variables;\n\nvariables[\"var\"] = 1;\nif(variables.find(\"jon\") == variables.end())\n std::cout << \"variable, \\\"jon\\\" not set\\n\";\n</code></pre>\n\n<p>In order to make this a variable like those used in PHP or javascript, the implementation would need to use some sort of variant type. </p>\n"
},
{
"answer_id": 231071,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 1,
"selected": false,
"text": "<p>As said in other answers, in C++ variables are never undefined. However, variables can be uninitialised, in which case their contents are not specified in the language standard (and implemented by most compilers to be whatever happened to be stored at that memory location).</p>\n\n<p>Normally a compiler offers a flag to detect possibly uninitialised variables, and will generate a warning if this is enabled.</p>\n\n<p>Another usage of isset could be to deal with different code. Remember that C++ is a statically compiled language, and attempting to redefine a symbol will result in a compile time error, removing the need for isset.</p>\n\n<p>Finally, what you might be looking for is a null pointer. For that, just use a simple comparison:</p>\n\n<pre><code>int * x(getFoo());\nif (x) {\n cout << \"Foo has a result.\" << endl;\n} else {\n cout << \"Foo returns null.\" << endl;\n}\n</code></pre>\n"
},
{
"answer_id": 231130,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>Short answer: <strong>NO</strong></p>\n\n<p>Standard followup question: What problem are you <strong>really</strong> trying to solve?</p>\n"
},
{
"answer_id": 231187,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Well there is always Boost.Optional</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_36_0/libs/optional/doc/html/index.html\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/optional/doc/html/index.html</a></p>\n\n<p>which should almost do what you want.</p>\n"
},
{
"answer_id": 231205,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 0,
"selected": false,
"text": "<p>You've got to separate two things here: variable <em>declaration</em> and variable <em>contents</em>.</p>\n\n<p>As said in other answers, unlike PHP, C++ doesn't allow a variable to be used before it's declared.</p>\n\n<p>But apart from that, it can be uninitialized.</p>\n\n<p>I think the PHP isset function tries to find out if a variable has a usable value. In C++, this corresponds best to a pointer being NULL or valid.</p>\n"
},
{
"answer_id": 231620,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The closest thing I can think of is to use pointers rather than real variables. Then you can check fro NULL.</p>\n\n<p>However, it does seem like you're solving wrong problem for the language, or using wrong language to solve your problem.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6561/"
] |
PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not.
Can we build similar feature for C/C++ (some kind of symbol table lookup)?
|
I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe).
You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously explicitly defined. There really is no such thing as an "unset" variable in C++.
Even if you say "int var;" and do not initialize it, the variable has a value, usually garbage, but it's still "set" in the PHP sense.
The closes I suppose would be the preprocessor's #ifdef and #ifndef which only checks to see if you've defined a variable using #define. But in my experience this is mostly used for omitting or adding code based on flags. For example:
```
// code code code
#ifdef DEBUG
// debug only code that will not be included in final product.
#endif
// more code more code
```
You can define DEBUG using #define to determine whether to include "DEBUG" code now.
Perhaps telling a bit more about what you're trying to do with the C++ equivalent of isset will give you a better idea of how to go about doing it "The C++ Way".
|
230,689 |
<p>I'd like a consistent and simple way to throw exceptions in JNI code; something that handles chained exceptions (implicitly from the env->ExceptionOccurred method, or explicitly by parameters, either way is good) and saves me looking up constructors every time I want to do this. All of the above is preferably in C, although I could translate it from C++ at need.</p>
<p>Does anyone on SO have something like this that they can share?</p>
|
[
{
"answer_id": 240506,
"author": "Steven M. Cherry",
"author_id": 24193,
"author_profile": "https://Stackoverflow.com/users/24193",
"pm_score": 7,
"selected": true,
"text": "<p>We just code utility methods for each of the types of exceptions we want to throw. Here are some examples:</p>\n\n\n\n<pre><code>jint throwNoClassDefError( JNIEnv *env, char *message )\n{\n jclass exClass;\n char *className = \"java/lang/NoClassDefFoundError\";\n\n exClass = (*env)->FindClass( env, className);\n if (exClass == NULL) {\n return throwNoClassDefError( env, className );\n }\n\n return (*env)->ThrowNew( env, exClass, message );\n}\n\njint throwNoSuchMethodError(\n JNIEnv *env, char *className, char *methodName, char *signature )\n{\n\n jclass exClass;\n char *exClassName = \"java/lang/NoSuchMethodError\" ;\n LPTSTR msgBuf;\n jint retCode;\n size_t nMallocSize;\n\n exClass = (*env)->FindClass( env, exClassName );\n if ( exClass == NULL ) {\n return throwNoClassDefError( env, exClassName );\n }\n\n nMallocSize = strlen(className) \n + strlen(methodName)\n + strlen(signature) + 8;\n\n msgBuf = malloc( nMallocSize );\n if ( msgBuf == NULL ) {\n return throwOutOfMemoryError\n ( env, \"throwNoSuchMethodError: allocating msgBuf\" );\n }\n memset( msgBuf, 0, nMallocSize );\n\n strcpy( msgBuf, className );\n strcat( msgBuf, \".\" );\n strcat( msgBuf, methodName );\n strcat( msgBuf, \".\" );\n strcat( msgBuf, signature );\n\n retCode = (*env)->ThrowNew( env, exClass, msgBuf );\n free ( msgBuf );\n return retCode;\n}\n\njint throwNoSuchFieldError( JNIEnv *env, char *message )\n{\n jclass exClass;\n char *className = \"java/lang/NoSuchFieldError\" ;\n\n exClass = (*env)->FindClass( env, className );\n if ( exClass == NULL ) {\n return throwNoClassDefError( env, className );\n }\n\n return (*env)->ThrowNew( env, exClass, message );\n}\n\njint throwOutOfMemoryError( JNIEnv *env, char *message )\n{\n jclass exClass;\n char *className = \"java/lang/OutOfMemoryError\" ;\n\n exClass = (*env)->FindClass( env, className );\n if ( exClass == NULL ) {\n return throwNoClassDefError( env, className );\n }\n\n return (*env)->ThrowNew( env, exClass, message );\n}\n</code></pre>\n\n<p>That way, it's easy to find them, your code-completion editor will help you to type them in, and you can pass simple parameters.</p>\n\n<p>I'm sure you could expand this to handle chained exceptions, or other more complicated approaches. This was enough to meet our needs.</p>\n"
},
{
"answer_id": 9812796,
"author": "Java42",
"author_id": 1250303,
"author_profile": "https://Stackoverflow.com/users/1250303",
"pm_score": 5,
"selected": false,
"text": "<p>I simply use 2 lines:</p>\n\n<pre><code> sprintf(exBuffer, \"NE%4.4X: Caller can %s %s print\", marker, \"log\", \"or\");\n (*env)->ThrowNew(env, (*env)->FindClass(env, \"java/lang/Exception\"), exBuffer);\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code> Exception in thread \"main\" java.lang.Exception: NE0042: Caller can log or print.\n</code></pre>\n"
},
{
"answer_id": 12215825,
"author": "android.weasel",
"author_id": 444234,
"author_profile": "https://Stackoverflow.com/users/444234",
"pm_score": 3,
"selected": false,
"text": "<p>My code starts in Java, invokes C++, which then invokes Java back again for things like finding, getting, and setting field values.</p>\n\n<p>In case someone looking for a C++ approach finds this page, I'll plough on with this:</p>\n\n<p>What I'm now doing is wrapping my JNI method bodies up with a C++ try/catch block,</p>\n\n<pre><code>JNIEXPORT void JNICALL Java_com_pany_jni_JNIClass_something(JNIEnv* env, jobject self)\n{\n try\n {\n ... do JNI stuff\n // return something; if not void.\n }\n catch (PendingException e) // (Should be &e perhaps?)\n {\n /* any necessary clean-up */\n }\n}\n</code></pre>\n\n<p>where PendingException is declared trivially:</p>\n\n<pre><code>class PendingException {};\n</code></pre>\n\n<p>and I'm invoking the following method after invoking any JNI from C++, so if the Java exception status indicates an error, I'll bail immediately and let the normal Java exception handling add the (Native method) line to the stack trace, while giving the C++ the opportunity to clean up while unwinding:</p>\n\n<pre><code>PendingException PENDING_JNI_EXCEPTION;\nvoid throwIfPendingException(JNIEnv* env)\n{\n if (env->ExceptionCheck()) {\n throw PENDING_JNI_EXCEPTION;\n }\n}\n</code></pre>\n\n<p>My Java stack trace looks like this for a failed env->GetFieldId() call:</p>\n\n<pre><code>java.lang.NoSuchFieldError: no field with name='opaque' signature='J' in class Lcom/pany/jni/JniClass;\n at com.pany.jni.JniClass.construct(Native Method)\n at com.pany.jni.JniClass.doThing(JniClass.java:169)\n at com.pany.jni.JniClass.access$1(JniClass.java:151)\n at com.pany.jni.JniClass$2.onClick(JniClass.java:129)\n at android.view.View.performClick(View.java:4084)\n</code></pre>\n\n<p>and pretty similar if I call up to a Java method that throws:</p>\n\n<pre><code> java.lang.RuntimeException: YouSuck\n at com.pany.jni.JniClass.fail(JniClass.java:35)\n at com.pany.jni.JniClass.getVersion(Native Method)\n at com.pany.jni.JniClass.doThing(JniClass.java:172)\n</code></pre>\n\n<p>I can't talk to wrapping the Java exception within another Java exception from within C++, which I think is part of your question - I've not found the need to do that - but if I did, I'd either do it with a Java-level wrapper around the native methods, or just extend my exception-throwing methods to take a jthrowable and replace the env->ThrowNew() call with something ugly: it's unfortunate Sun didn't provide a version of ThrowNew that took a jthrowable.</p>\n\n<pre><code>void impendNewJniException(JNIEnv* env, const char *classNameNotSignature, const char *message)\n{\n jclass jClass = env->FindClass(classNameNotSignature);\n throwIfPendingException(env);\n env->ThrowNew(jClass, message);\n}\n\nvoid throwNewJniException(JNIEnv* env, const char* classNameNotSignature, const char* message)\n{\n impendNewJniException(env, classNameNotSignature, message);\n throwIfPendingException(env);\n}\n</code></pre>\n\n<p>I wouldn't consider caching (exception) class constructor references because exceptions aren't supposed to be a usual control flow mechanism, so it shouldn't matter if they're slow. I imagine look-up isn't terribly slow anyway, since Java presumably does its own caching for that sort of thing.</p>\n"
},
{
"answer_id": 53961548,
"author": "Canato",
"author_id": 3117650,
"author_profile": "https://Stackoverflow.com/users/3117650",
"pm_score": 2,
"selected": false,
"text": "<p>I will put a more complete and general answer for who need a little bit more explanations like I need before.</p>\n\n<p>First is nice to set your method with a <code>Throw Exception</code> so the IDE will ask for try/catch.</p>\n\n<pre><code>public native int func(Param1, Param2, Param3) throws IOException;\n</code></pre>\n\n<p>I decide for <code>IOException</code> over <code>Exception</code> because of <a href=\"https://stackoverflow.com/a/5899901/3117650\">this</a>.</p>\n\n<pre><code>JNIEXPORT int JNICALL Java_YourClass_func\n(int Param1, int Param2, int Param3) {\n if (Param3 == 0) { //something wrong\n jclass Exception = env->FindClass(\"java/lang/Exception\");\n env->ThrowNew(Exception, \"Can't divide by zero.\"); // Error Message\n }\n return (Param1+Param2)/Param3;\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
I'd like a consistent and simple way to throw exceptions in JNI code; something that handles chained exceptions (implicitly from the env->ExceptionOccurred method, or explicitly by parameters, either way is good) and saves me looking up constructors every time I want to do this. All of the above is preferably in C, although I could translate it from C++ at need.
Does anyone on SO have something like this that they can share?
|
We just code utility methods for each of the types of exceptions we want to throw. Here are some examples:
```
jint throwNoClassDefError( JNIEnv *env, char *message )
{
jclass exClass;
char *className = "java/lang/NoClassDefFoundError";
exClass = (*env)->FindClass( env, className);
if (exClass == NULL) {
return throwNoClassDefError( env, className );
}
return (*env)->ThrowNew( env, exClass, message );
}
jint throwNoSuchMethodError(
JNIEnv *env, char *className, char *methodName, char *signature )
{
jclass exClass;
char *exClassName = "java/lang/NoSuchMethodError" ;
LPTSTR msgBuf;
jint retCode;
size_t nMallocSize;
exClass = (*env)->FindClass( env, exClassName );
if ( exClass == NULL ) {
return throwNoClassDefError( env, exClassName );
}
nMallocSize = strlen(className)
+ strlen(methodName)
+ strlen(signature) + 8;
msgBuf = malloc( nMallocSize );
if ( msgBuf == NULL ) {
return throwOutOfMemoryError
( env, "throwNoSuchMethodError: allocating msgBuf" );
}
memset( msgBuf, 0, nMallocSize );
strcpy( msgBuf, className );
strcat( msgBuf, "." );
strcat( msgBuf, methodName );
strcat( msgBuf, "." );
strcat( msgBuf, signature );
retCode = (*env)->ThrowNew( env, exClass, msgBuf );
free ( msgBuf );
return retCode;
}
jint throwNoSuchFieldError( JNIEnv *env, char *message )
{
jclass exClass;
char *className = "java/lang/NoSuchFieldError" ;
exClass = (*env)->FindClass( env, className );
if ( exClass == NULL ) {
return throwNoClassDefError( env, className );
}
return (*env)->ThrowNew( env, exClass, message );
}
jint throwOutOfMemoryError( JNIEnv *env, char *message )
{
jclass exClass;
char *className = "java/lang/OutOfMemoryError" ;
exClass = (*env)->FindClass( env, className );
if ( exClass == NULL ) {
return throwNoClassDefError( env, className );
}
return (*env)->ThrowNew( env, exClass, message );
}
```
That way, it's easy to find them, your code-completion editor will help you to type them in, and you can pass simple parameters.
I'm sure you could expand this to handle chained exceptions, or other more complicated approaches. This was enough to meet our needs.
|
230,715 |
<p>Alright, after doing a ton of research and trying almost every managed CPP Redist I can find as well as trying to copy my DLLs locally to the executing directory of the app I cannot figure out what dependencies i'm missing for this mixed mode library.</p>
<p>Basically I have a large C# application and I'm trying to use a mixed mode library I made. On the development machine it works perfect (of course) but deployed when the library needs to be loaded for use it exceptions out because of missing CRT dependencies (I assume).</p>
<p>I have used dependency walker to check all the DLLs referenced and ensured they exist on the deployment machine with no luck, I'm wondering if maybe it's some dependencies that need to be registered that I am missing, but i can't figure out what.</p>
<p>I get the following exception when code tries to instantiate a class from the mixed mode library.</p>
<blockquote>
<p>Exception Detail:
System.IO.FileLoadException: Could not
load file or assembly 'USADSI.MAPI,
Version=1.0.3174.25238,
Culture=neutral, PublicKeyToken=null'
or one of its dependencies. This
application has failed to start
because the application configuration
is incorrect. Reinstalling the
application may fix this problem.
(Exception from HRESULT: 0x800736B1)</p>
</blockquote>
<p>I am compiling the library using VS2008 SP1 with /clr:oldSyntax specified.</p>
<p>The intermediate manifest looks like this:</p>
<pre><code><assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level='asInvoker' uiAccess='false' />
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
</code></pre>
<p>I can provide any more information as needed, unfortunately i'm not well versed in making mixed mode libraries so this has thrown me off.</p>
<p>If anyone can offer any advice I would greatly appreciate it!</p>
|
[
{
"answer_id": 231117,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 3,
"selected": true,
"text": "<p>Did you deploy the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en\" rel=\"nofollow noreferrer\">CRT libraries</a> on the target machine? Long shot: since you have a dependency on 32-bit code, you should set Target Platform in the Build property tab to x86.</p>\n\n<p>EDIT: trouble-shoot side-by-side resolving problems with the <a href=\"http://blogs.msdn.com/junfeng/archive/2006/04/14/576314.aspx\" rel=\"nofollow noreferrer\">Sxstrace.exe utility</a>, available on Vista.</p>\n"
},
{
"answer_id": 231410,
"author": "Coderer",
"author_id": 26286,
"author_profile": "https://Stackoverflow.com/users/26286",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar problem the first time I deployed a VS 2005 app on a target machine -- had to bring over the MSVCRT80 DLL. Are you saying you already have the 2008 VS runtime library there?</p>\n\n<p>ETA: Also, dumb question, but are you sure you have both the CRT Runtime (linked to above) <em>and</em> the .NET Runtime, with the same version you compiled against (probably 3.5)? You probably already know this (especially considering your score) but they're 2 different things.</p>\n"
},
{
"answer_id": 231427,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 1,
"selected": false,
"text": "<p>I found a solution that seems to work although I don't like it very much.</p>\n\n<p>I had to copy the folders:</p>\n\n<p>Microsoft.VC90.CRT & Microsoft.VC90.MFC</p>\n\n<p>From: Program Files\\Microsoft Visual Studio 9.0\\VC\\redist\\x86</p>\n\n<p>Into the deployed application directory, I just can't figure out why this seems to work and the redistributables did nothing.</p>\n\n<p>EDIT: Looking at the manifest I probably don't need to copy the MFC directory</p>\n"
},
{
"answer_id": 260349,
"author": "morechilli",
"author_id": 5427,
"author_profile": "https://Stackoverflow.com/users/5427",
"pm_score": 1,
"selected": false,
"text": "<p>Best way to solve this problem is to download process monitor which is free from:\n<a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx</a></p>\n\n<p>Add a filter to watch only your process and it will show you all file access the process tries. This will show you exactly which dll it can't find.</p>\n\n<p>I always use this when faced with the same problem - if only microsoft filled in the filename in the thrown exception it would all be easier.</p>\n"
},
{
"answer_id": 938375,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 2,
"selected": false,
"text": "<p>Typically I've found that the <a href=\"http://blogs.msdn.com/oldnewthing/archive/2007/05/31/2995284.aspx\" rel=\"nofollow noreferrer\">pragma comment</a> style manifest decleration's to be much more error free, from a developer maintenence and an over all build action perspective. The XML manifest's are <a href=\"http://blogs.msdn.com/vcblog/archive/2008/08/12/bugs-fixed-in-mfc-in-visual-studio-2008-sp1.aspx\" rel=\"nofollow noreferrer\">natoriously snafu</a>.</p>\n\n<p>The fimiluarity with how the linker operates and the usual compilation of C code and the fact that you simply tak this in, onto one of your source files, keeps everything a bit feeling more \"together\";</p>\n\n<pre><code>#pragma comment(linker, \\\n \"\\\"/manifestdependency:type='Win32' \"\\\n \"name='Microsoft.Windows.Common-Controls' \"\\\n \"version='6.0.0.0' \"\\\n \"processorArchitecture='*' \"\\\n \"publicKeyToken='6595b64144ccf1df' \"\\\n \"language='*'\\\"\")\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12707/"
] |
Alright, after doing a ton of research and trying almost every managed CPP Redist I can find as well as trying to copy my DLLs locally to the executing directory of the app I cannot figure out what dependencies i'm missing for this mixed mode library.
Basically I have a large C# application and I'm trying to use a mixed mode library I made. On the development machine it works perfect (of course) but deployed when the library needs to be loaded for use it exceptions out because of missing CRT dependencies (I assume).
I have used dependency walker to check all the DLLs referenced and ensured they exist on the deployment machine with no luck, I'm wondering if maybe it's some dependencies that need to be registered that I am missing, but i can't figure out what.
I get the following exception when code tries to instantiate a class from the mixed mode library.
>
> Exception Detail:
> System.IO.FileLoadException: Could not
> load file or assembly 'USADSI.MAPI,
> Version=1.0.3174.25238,
> Culture=neutral, PublicKeyToken=null'
> or one of its dependencies. This
> application has failed to start
> because the application configuration
> is incorrect. Reinstalling the
> application may fix this problem.
> (Exception from HRESULT: 0x800736B1)
>
>
>
I am compiling the library using VS2008 SP1 with /clr:oldSyntax specified.
The intermediate manifest looks like this:
```
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level='asInvoker' uiAccess='false' />
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
```
I can provide any more information as needed, unfortunately i'm not well versed in making mixed mode libraries so this has thrown me off.
If anyone can offer any advice I would greatly appreciate it!
|
Did you deploy the [CRT libraries](http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en) on the target machine? Long shot: since you have a dependency on 32-bit code, you should set Target Platform in the Build property tab to x86.
EDIT: trouble-shoot side-by-side resolving problems with the [Sxstrace.exe utility](http://blogs.msdn.com/junfeng/archive/2006/04/14/576314.aspx), available on Vista.
|
230,716 |
<p>I'm using C# & .NEt 3.5. What is the difference between the OptionA and OptionB ?</p>
<pre><code>class MyClass
{
private object m_Locker = new object();
private Dicionary<string, object> m_Hash = new Dictionary<string, object>();
public void OptionA()
{
lock(m_Locker){
// Do something with the dictionary
}
}
public void OptionB()
{
lock(m_Hash){
// Do something with the dictionary
}
}
}
</code></pre>
<p>I'm starting to dabble in threading (primarly for creating a cache for a multi-threaded app, NOT using the HttpCache class, since it's not attached to a web site), and I see the OptionA syntax in a lot of the examples I see online, but I don't understand what, if any, reason that is done over OptionB.</p>
|
[
{
"answer_id": 230752,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 2,
"selected": false,
"text": "<p>It's not what you're \"Locking\", its the code that's contained between the lock { ... } thats important and that you're preventing from being executed.</p>\n\n<p>If one thread takes out a lock() on any object, it prevents other threads from obtaining a lock on the same object, and hence prevents the second thread from executing the code between the braces.</p>\n\n<p>So that's why most people just create a junk object to lock on, it prevents other threads from obtaining a lock on that same junk object.</p>\n"
},
{
"answer_id": 230753,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 6,
"selected": true,
"text": "<p>Option B uses the object to be protected to create a critical section. In some cases, this more clearly communicates the intent. If used consistently, it guarantees only one critical section for the protected object will be active at a time:</p>\n\n<pre><code>lock (m_Hash)\n{\n // Across all threads, I can be in one and only one of these two blocks\n // Do something with the dictionary\n}\nlock (m_Hash)\n{\n // Across all threads, I can be in one and only one of these two blocks\n // Do something with the dictionary\n}\n</code></pre>\n\n<p>Option A is less restrictive. It uses a secondary object to create a critical section for the object to be protected. If multiple secondary objects are used, it's possible to have more than one critical section for the protected object active at a time.</p>\n\n<pre><code>private object m_LockerA = new object();\nprivate object m_LockerB = new object();\n\nlock (m_LockerA)\n{\n // It's possible this block is active in one thread\n // while the block below is active in another\n // Do something with the dictionary\n}\nlock (m_LockerB)\n{\n // It's possible this block is active in one thread\n // while the block above is active in another\n // Do something with the dictionary\n}\n</code></pre>\n\n<p>Option A is equivalent to Option B if you use only one secondary object. As far as reading code, Option B's intent is clearer. If you're protecting more than one object, Option B isn't really an option.</p>\n"
},
{
"answer_id": 230766,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 1,
"selected": false,
"text": "<p>Well, it depends on what you wanted to lock(be made threadsafe).</p>\n\n<p>Normally I would choose OptionB to provide threadsafe access to m_Hash ONLY. Where as OptionA, I would used for locking value type, which can't be used with the lock, or I had a group of objects that need locking concurrently, but I don't what to lock the whole instance by using <code>lock(this)</code></p>\n"
},
{
"answer_id": 230784,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>Locking the object that you're using is simply a matter of convenience. An external lock object <em>can</em> make things simpler, and is also needed if the shared resource is private, like with a collection (in which case you use the <code>ICollection.SyncRoot</code> object). </p>\n"
},
{
"answer_id": 230861,
"author": "Daniel Plaisted",
"author_id": 1509,
"author_profile": "https://Stackoverflow.com/users/1509",
"pm_score": 4,
"selected": false,
"text": "<p>It's important to understand that lock(m_Hash) does <em>NOT</em> prevent other code from using the hash. It only prevents other code from running that is also using m_Hash as its locking object.</p>\n\n<p>One reason to use option A is because classes are likely to have private variables that you will use inside the lock statement. It is much easier to just use one object which you use to lock access to all of them instead of trying to use finer grain locks to lock access to just the members you will need. If you try to go with the finer grained method you will probably have to take multiple locks in some situations and then you need to make sure you are always taking them in the same order to avoid deadlocks.</p>\n\n<p>Another reason to use option A is because it is possible that the reference to m_Hash will be accessible outside your class. Perhaps you have a public property which supplies access to it, or maybe you declare it as protected and derived classes can use it. In either case once external code has a reference to it, it is possible that the external code will use it for a lock. This also opens up the possibility of deadlocks since you have no way to control or know what order the lock will be taken in.</p>\n"
},
{
"answer_id": 230883,
"author": "VirtualStaticVoid",
"author_id": 30521,
"author_profile": "https://Stackoverflow.com/users/30521",
"pm_score": 2,
"selected": false,
"text": "<p>I think the scope of the variable you \"pass\" in will determine the scope of the lock.\ni.e. An instance variable will be in respect of the instance of the class whereas a static variable will be for the whole AppDomain.</p>\n\n<p>Looking at the implementation of the collections (using Reflector), the pattern seems to follow that an instance variable called SyncRoot is declared and used for all locking operations in respect of the instance of the collection.</p>\n"
},
{
"answer_id": 8922406,
"author": "D.P.",
"author_id": 1063480,
"author_profile": "https://Stackoverflow.com/users/1063480",
"pm_score": 3,
"selected": false,
"text": "<p>Actually, it is not good idea to lock on object if you are using its members.\nJeffrey Richter wrote in his book \"CLR via C#\" that there is no guarantee that a class of object that you are using for synchronization will not use <code>lock(this)</code> in its implementation (It's interesting, but it was a recommended way for synchronization by Microsoft for some time... Then, they found that it was a mistake), so it is always a good idea to use a special separate object for synchronization. So, as you can see OptionB will not give you a guarantee of deadlock - safety. \nSo, OptionA is much safer that OptionB.</p>\n"
},
{
"answer_id": 33261655,
"author": "John Demetriou",
"author_id": 1766548,
"author_profile": "https://Stackoverflow.com/users/1766548",
"pm_score": 0,
"selected": false,
"text": "<p>OptionA is the way to go here as long as in all your code, when accessing the m_hash you use the m_Locker to lock on it.</p>\n\n<p>Now Imagine this case. You lock on the object. And that object in one of the functions you call has a <code>lock(this)</code> code segment. In this case that is a sure unrecoverable deadlock</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17803/"
] |
I'm using C# & .NEt 3.5. What is the difference between the OptionA and OptionB ?
```
class MyClass
{
private object m_Locker = new object();
private Dicionary<string, object> m_Hash = new Dictionary<string, object>();
public void OptionA()
{
lock(m_Locker){
// Do something with the dictionary
}
}
public void OptionB()
{
lock(m_Hash){
// Do something with the dictionary
}
}
}
```
I'm starting to dabble in threading (primarly for creating a cache for a multi-threaded app, NOT using the HttpCache class, since it's not attached to a web site), and I see the OptionA syntax in a lot of the examples I see online, but I don't understand what, if any, reason that is done over OptionB.
|
Option B uses the object to be protected to create a critical section. In some cases, this more clearly communicates the intent. If used consistently, it guarantees only one critical section for the protected object will be active at a time:
```
lock (m_Hash)
{
// Across all threads, I can be in one and only one of these two blocks
// Do something with the dictionary
}
lock (m_Hash)
{
// Across all threads, I can be in one and only one of these two blocks
// Do something with the dictionary
}
```
Option A is less restrictive. It uses a secondary object to create a critical section for the object to be protected. If multiple secondary objects are used, it's possible to have more than one critical section for the protected object active at a time.
```
private object m_LockerA = new object();
private object m_LockerB = new object();
lock (m_LockerA)
{
// It's possible this block is active in one thread
// while the block below is active in another
// Do something with the dictionary
}
lock (m_LockerB)
{
// It's possible this block is active in one thread
// while the block above is active in another
// Do something with the dictionary
}
```
Option A is equivalent to Option B if you use only one secondary object. As far as reading code, Option B's intent is clearer. If you're protecting more than one object, Option B isn't really an option.
|
230,718 |
<p>I was wondering if there's a way to see the output of any command,
straight inside vim, rather than first redirecting it into a file and
then opening that file.</p>
<p>E.x. I need something like
$ gvim < <code>diff -r dir1/ dir2/</code></p>
<p>This gives ambiguous redirect error message</p>
<p>I just want to see the diffs between dir1 and dir2 straight inside
gvim.</p>
<p>Can any one provide a nice hack?</p>
|
[
{
"answer_id": 230731,
"author": "Aditya Mukherji",
"author_id": 25990,
"author_profile": "https://Stackoverflow.com/users/25990",
"pm_score": 2,
"selected": false,
"text": "<p>jst use gvimdiff instead<br>\nor vimdiff <br>\nto paste the output of a command straight into vim, for example ls, try<br>\n:%r!ls</p>\n"
},
{
"answer_id": 230739,
"author": "jvasak",
"author_id": 5840,
"author_profile": "https://Stackoverflow.com/users/5840",
"pm_score": 5,
"selected": false,
"text": "<pre><code>diff file1 file2 | vim -R -\n</code></pre>\n\n<p>The <code>-R</code> makes it read-only so you don't accidentally modify the input (which may or may not be your desired behavior). The single dash tells <code>vim</code> to reads its input over standard input. Works for other commands, too.</p>\n"
},
{
"answer_id": 230794,
"author": "Peter Stone",
"author_id": 1806,
"author_profile": "https://Stackoverflow.com/users/1806",
"pm_score": 3,
"selected": false,
"text": "<p><code>vim -d file1 file2</code></p>\n"
},
{
"answer_id": 230941,
"author": "skinp",
"author_id": 2907,
"author_profile": "https://Stackoverflow.com/users/2907",
"pm_score": 3,
"selected": false,
"text": "<p>Also, when already in Vim:</p>\n\n<pre><code>:r! diff file1 file2\n</code></pre>\n"
},
{
"answer_id": 231118,
"author": "Walter",
"author_id": 23840,
"author_profile": "https://Stackoverflow.com/users/23840",
"pm_score": 3,
"selected": false,
"text": "<p>Although I would also suggest <code>vimdiff</code> or <code>vim -d</code> for the case of looking at a diff, I just have to share this (more general) approach for using vim usage in pipes: vipe (from the <code>moreutils</code> package in Ubuntu).</p>\n\n<p>For example:</p>\n\n<blockquote>\n <p>find -name '*.png' | vipe | xargs rm</p>\n</blockquote>\n\n<p>would allow you to first edit (in vim) the list of .png files found before passing it to <code>xargs rm</code>.</p>\n"
},
{
"answer_id": 231769,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 2,
"selected": false,
"text": "<p>BTW, there is a <a href=\"http://www.vim.org/scripts/script.php?script_id=102\" rel=\"nofollow noreferrer\">DirDiff plugin</a>.</p>\n"
},
{
"answer_id": 941629,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this with </p>\n\n<pre><code>diff -r dir1/ dir2/ | gvim -\n</code></pre>\n\n<p>the '<code>-</code>' option to vim (or gvim) tells vim to open STDIN</p>\n"
},
{
"answer_id": 7132868,
"author": "ajwood",
"author_id": 512652,
"author_profile": "https://Stackoverflow.com/users/512652",
"pm_score": 1,
"selected": false,
"text": "<p>I often use <code>vimdiff -g <file1> <file2></code></p>\n"
},
{
"answer_id": 13970626,
"author": "VineetChirania",
"author_id": 1746474,
"author_profile": "https://Stackoverflow.com/users/1746474",
"pm_score": 0,
"selected": false,
"text": "<p>One of the most simple and convenient ways is to do it like this:</p>\n\n<pre><code>vimdiff -R <file1> <file2>\n</code></pre>\n\n<p>Again the '-R' flag is to open it for read-only mode to avoid any accidental changes.</p>\n"
},
{
"answer_id": 25632528,
"author": "drrossum",
"author_id": 839485,
"author_profile": "https://Stackoverflow.com/users/839485",
"pm_score": 0,
"selected": false,
"text": "<p>What you are looking for is called <a href=\"http://wiki.bash-hackers.org/syntax/expansion/proc_subst\" rel=\"nofollow\">process substitution</a>:</p>\n\n<p><code>vim <(diff -r dir1/ dir2/)</code></p>\n\n<p>But the DirDiff plugin mentioned by Luc is much more useful for comparing directories.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I was wondering if there's a way to see the output of any command,
straight inside vim, rather than first redirecting it into a file and
then opening that file.
E.x. I need something like
$ gvim < `diff -r dir1/ dir2/`
This gives ambiguous redirect error message
I just want to see the diffs between dir1 and dir2 straight inside
gvim.
Can any one provide a nice hack?
|
```
diff file1 file2 | vim -R -
```
The `-R` makes it read-only so you don't accidentally modify the input (which may or may not be your desired behavior). The single dash tells `vim` to reads its input over standard input. Works for other commands, too.
|
230,724 |
<p>I'm using a small site to experiment with the uploading of pictures and displaying them.</p>
<p>When someone clicks "add a picture", they get taken to a page with a form on it. They can select a file and click the submit button.</p>
<p>But what I want to do now is this: put a second submit button labeled "Cancel" next to the normal confirmation button. If someone then chooses to upload, selects and hits submit, if they press the cancel button before the file is fully uploaded, PHP should stop the uploading of the file and delete it. And then just go back to the overview.</p>
<p>No Javascript used whatsoever.</p>
<p>I only have localhost, so testing this in kindof impossible, since I just copy a file the millisecond I press the submit button. There's no upload-time with a localhost and I'm not going to buy a server somewhere just for this.</p>
<p>Basically what's happening now is that the PHP detects which button was sent. If the submit button was sent, the file is uploaded, if the cancel button is sent, it just goes back to the overview.</p>
<p>But PHP does its tasks one in a row. So I don't think this will work. How do I tell PHP to stop doing the upload?</p>
|
[
{
"answer_id": 230748,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "<p>You can't look at the button with php - the whole request will have been sent before PHP gets that information.</p>\n\n<p>What you could do is put the cancel button in a different <code><form></code>, like this:</p>\n\n<pre><code><form> <input type=\"file> <input type=\"submit\" value=\"upload\"> </form>\n<form> <input type=\"submit\" value=\"cancel\"> </form>\n</code></pre>\n\n<p>(This is just an example of course - there's bits missing).</p>\n\n<p>When they click cancel, the browser should abandon its request and start a new one, cancelling the upload.</p>\n"
},
{
"answer_id": 231646,
"author": "Sherm Pendley",
"author_id": 27631,
"author_profile": "https://Stackoverflow.com/users/27631",
"pm_score": 0,
"selected": false,
"text": "<p>There's no way for PHP to stop a file upload in progress. Your PHP code isn't even started until the file upload is done, so by the time it's running, it's too late.</p>\n"
},
{
"answer_id": 250386,
"author": "Daan",
"author_id": 7922,
"author_profile": "https://Stackoverflow.com/users/7922",
"pm_score": 0,
"selected": false,
"text": "<p>If it indeed turns out that cancelling the upload is not possible, you might consider implementing an easy to use undo or delete function, so that users can immediately undo the uploading of the image (i.e. the image is deleted). This may not be useful in your experiment, but perhaps you can use it in a production application? </p>\n"
},
{
"answer_id": 949539,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Greg has the right idea there.\nIn stead of following the majority, or looking at how things are done, look at smart alternatives, like Greg's explanation above.</p>\n\n<p>Any upload cannot function without a valid link between the client and the server; hence if you close your browser window, or re-direct it to some place else, the upload is killed.</p>\n\n<p>use an iframe and name it eg.: \"myframe\". you can easily hide it in a div. have a form with your action=\"somefile.php\" and target=\"myframe\". add a lil Javascript to your form's \"file\" field: onFocus=\"uploadlistener()\". you can name this function anything you like, but use it to check if the person \"opened\" anything. the browser will automatically swap focus, whether, the user clicked \"browse\", or if he then opened a file. difference is, after a file has been \"selected\", the input field receives the focus again, but remember you have a listener on the \"onFocus()\" event. so: if the field is not empty, call: document.uploadform.submit()</p>\n\n<p>Using this method, you don't even need a submit button. if you want to skin your \"browse\" button, just make it transparent using CSS, eg:\ninput name=\"myfile\" type=\"file\" style=\"width: 40px; -moz-opacity: 0; filter: alpha(opacity=0)\" onFocus=\"somefunction()\"\nWell to cancel upload just redirect the iframe to some other place, eg:\ninput type=\"button\" value=\"cancel\" onClick=\"document.uploadform.action='blank.php'; document.uploadform.submit()\"</p>\n\n<p>Pardon if the html above spans across multiple lines, it's the first time I'm posting here.</p>\n\n<p>To track progress, you need to add a server side listener, either with PHP-5.2, or some Perl script to check how many bytes have been loaded thus far of the total file size checked before upload was started. this check interval can be achived with some AJAX, or if you don't know the term, look up: HTTP-REQUEST. this runs server side code in the background and outputs a response like you would see in the browser, but here you can capture it in a variable, and do your stuff. I hope this was helpful to anyone.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
I'm using a small site to experiment with the uploading of pictures and displaying them.
When someone clicks "add a picture", they get taken to a page with a form on it. They can select a file and click the submit button.
But what I want to do now is this: put a second submit button labeled "Cancel" next to the normal confirmation button. If someone then chooses to upload, selects and hits submit, if they press the cancel button before the file is fully uploaded, PHP should stop the uploading of the file and delete it. And then just go back to the overview.
No Javascript used whatsoever.
I only have localhost, so testing this in kindof impossible, since I just copy a file the millisecond I press the submit button. There's no upload-time with a localhost and I'm not going to buy a server somewhere just for this.
Basically what's happening now is that the PHP detects which button was sent. If the submit button was sent, the file is uploaded, if the cancel button is sent, it just goes back to the overview.
But PHP does its tasks one in a row. So I don't think this will work. How do I tell PHP to stop doing the upload?
|
You can't look at the button with php - the whole request will have been sent before PHP gets that information.
What you could do is put the cancel button in a different `<form>`, like this:
```
<form> <input type="file> <input type="submit" value="upload"> </form>
<form> <input type="submit" value="cancel"> </form>
```
(This is just an example of course - there's bits missing).
When they click cancel, the browser should abandon its request and start a new one, cancelling the upload.
|
230,736 |
<p>Is it possible for a generic interface's type to be based on a specific parent class?</p>
<p>For example:</p>
<pre><code>public interface IGenericFace<T : BaseClass>
{
}
</code></pre>
<p>Obviously the above code doesn't work but if it did, what I'm trying to tell the compiler is that <code>T</code> must be a sub-class of <code>BaseClass</code>. Can that be done, are there plans for it, etc.?</p>
<p>I think it would be useful in terms of a specific project, making sure a generic interface/class isn't used with unintended type(s) at compile time. Or also to sort of self-document: show what kind of type is intended.</p>
|
[
{
"answer_id": 230742,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 8,
"selected": true,
"text": "<pre><code>public interface IGenericFace<T> where T : SomeBaseClass\n</code></pre>\n"
},
{
"answer_id": 230749,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>yes.</p>\n\n<pre><code>public interface IGenericFace<T>\n where T : BaseClass\n{\n}\n</code></pre>\n"
},
{
"answer_id": 230805,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 6,
"selected": false,
"text": "<p>What your are referring to is called \"Generic Constraints\". There are numerous constraints that can be put on a generic type.</p>\n\n<p>Some basic examples are as follows:</p>\n\n<ul>\n<li><p><code>where T: struct</code> - The type argument must be a value type. Any value type except <code>Nullable</code> - can be specified. See <a href=\"http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx\" rel=\"noreferrer\">Using Nullable Types (C# Programming Guide)</a> for more information. </p></li>\n<li><p><code>where T : class</code> - The type argument must be a reference type; this applies also to any class, interface, delegate, or array type. </p></li>\n<li><p><code>where T : new()</code> - The type argument must have a public parameterless constructor. When used together with other constraints, the <code>new()</code> constraint must be specified last. </p></li>\n<li><p><code>where T : <base class name></code> - The type argument must be or derive from the specified base class. </p></li>\n<li><p><code>where T : <interface name></code> - The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic. </p></li>\n<li><p><code>where T : U</code> - The type argument supplied for <code>T</code> must be or derive from the argument supplied for <code>U</code>. This is called a naked type constraint. </p></li>\n</ul>\n\n<p>These can also be linked together like this:</p>\n\n<p>C#</p>\n\n<pre><code>public class TestClass<T> where T : MyBaseClass, INotifyPropertyChanged, new() { }\npublic interface IGenericFace<T> where T : SomeBaseClass\n</code></pre>\n\n<p>VB</p>\n\n<pre><code>Public Class TestClass(Of T As {MyBaseClass, INotifyPropertyChanged, New})\nPublic Interface IGenericInterface(Of T As SomeBaseClass)\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
Is it possible for a generic interface's type to be based on a specific parent class?
For example:
```
public interface IGenericFace<T : BaseClass>
{
}
```
Obviously the above code doesn't work but if it did, what I'm trying to tell the compiler is that `T` must be a sub-class of `BaseClass`. Can that be done, are there plans for it, etc.?
I think it would be useful in terms of a specific project, making sure a generic interface/class isn't used with unintended type(s) at compile time. Or also to sort of self-document: show what kind of type is intended.
|
```
public interface IGenericFace<T> where T : SomeBaseClass
```
|
230,751 |
<p>How do I force Python's <code>print</code> function to flush the buffered output to the screen?</p>
|
[
{
"answer_id": 230774,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 12,
"selected": true,
"text": "<p>In Python 3, <a href=\"https://docs.python.org/library/functions.html#print\" rel=\"noreferrer\"><code>print</code></a> can take an optional <code>flush</code> argument:</p>\n<pre><code>print("Hello, World!", flush=True)\n</code></pre>\n<p>In Python 2, after calling <code>print</code>, do:</p>\n<pre><code>import sys\nsys.stdout.flush()\n</code></pre>\n<p>By default, <a href=\"https://docs.python.org/2/reference/simple_stmts.html#the-print-statement\" rel=\"noreferrer\"><code>print</code></a> prints to <a href=\"https://docs.python.org/2/library/sys.html#sys.stdout\" rel=\"noreferrer\"><code>sys.stdout</code></a> (see the documentation for more about <a href=\"https://docs.python.org/2/library/stdtypes.html#file-objects\" rel=\"noreferrer\">file objects</a>).</p>\n"
},
{
"answer_id": 230780,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 9,
"selected": false,
"text": "<p>Running <code>python -h</code>, I see a <em>command line option</em>:</p>\n<blockquote>\n<p>-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x\nsee man page for details on internal buffering relating to '-u'</p>\n</blockquote>\n<p>Here is the <a href=\"http://docs.python.org/using/cmdline.html#cmdoption-u\" rel=\"noreferrer\">relevant documentation</a>.</p>\n"
},
{
"answer_id": 231216,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 5,
"selected": false,
"text": "<p>Using the <code>-u</code> command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the <code>-u</code> option. I usually use a custom <code>stdout</code>, like this:</p>\n\n<pre><code>class flushfile:\n def __init__(self, f):\n self.f = f\n\n def write(self, x):\n self.f.write(x)\n self.f.flush()\n\nimport sys\nsys.stdout = flushfile(sys.stdout)\n</code></pre>\n\n<p>... Now all your <code>print</code> calls (which use <code>sys.stdout</code> implicitly), will be automatically <code>flush</code>ed.</p>\n"
},
{
"answer_id": 288536,
"author": "Kamil Kisiel",
"author_id": 15061,
"author_profile": "https://Stackoverflow.com/users/15061",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/230751/how-can-i-flush-the-output-of-the-print-function/231216#231216\">Dan's idea</a> doesn't quite work:</p>\n<pre><code>#!/usr/bin/env python\nclass flushfile(file):\n def __init__(self, f):\n self.f = f\n def write(self, x):\n self.f.write(x)\n self.f.flush()\n\nimport sys\nsys.stdout = flushfile(sys.stdout)\n\nprint "foo"\n</code></pre>\n<p>The result:</p>\n<pre><code>Traceback (most recent call last):\n File "./passpersist.py", line 12, in <module>\n print "foo"\nValueError: I/O operation on closed file\n</code></pre>\n<p>I believe the problem is that it inherits from the file class, which actually isn't necessary. According to the documentation for sys.stdout:</p>\n<blockquote>\n<p>stdout and stderr needn’t be built-in\nfile objects: any object is acceptable\nas long as it has a write() method\nthat takes a string argument.</p>\n</blockquote>\n<p>so changing</p>\n<pre><code>class flushfile(file):\n</code></pre>\n<p>to</p>\n<pre><code>class flushfile(object):\n</code></pre>\n<p>makes it work just fine.</p>\n"
},
{
"answer_id": 741601,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Use an unbuffered file:</p>\n<pre><code>f = open('xyz.log', 'a', 0)\n</code></pre>\n<p><em>Or</em></p>\n<pre><code>sys.stdout = open('out.log', 'a', 0)\n</code></pre>\n"
},
{
"answer_id": 6055744,
"author": "guettli",
"author_id": 633961,
"author_profile": "https://Stackoverflow.com/users/633961",
"pm_score": 4,
"selected": false,
"text": "<p>Here is my version, which provides writelines() and fileno(), too:</p>\n\n<pre><code>class FlushFile(object):\n def __init__(self, fd):\n self.fd = fd\n\n def write(self, x):\n ret = self.fd.write(x)\n self.fd.flush()\n return ret\n\n def writelines(self, lines):\n ret = self.writelines(lines)\n self.fd.flush()\n return ret\n\n def flush(self):\n return self.fd.flush\n\n def close(self):\n return self.fd.close()\n\n def fileno(self):\n return self.fd.fileno()\n</code></pre>\n"
},
{
"answer_id": 9462099,
"author": "Antony Hatchkins",
"author_id": 237105,
"author_profile": "https://Stackoverflow.com/users/237105",
"pm_score": 6,
"selected": false,
"text": "<p>Also, as suggested in <a href=\"http://algorithmicallyrandom.blogspot.com/2009/10/python-tips-and-tricks-flushing-stdout.html\" rel=\"nofollow noreferrer\">this blog post</a>, one can reopen <code>sys.stdout</code> in unbuffered mode:</p>\n<pre><code>sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n</code></pre>\n<p>Each <code>stdout.write</code> and <code>print</code> operation will be automatically flushed afterwards.</p>\n"
},
{
"answer_id": 23142556,
"author": "Eugene Sajine",
"author_id": 673423,
"author_profile": "https://Stackoverflow.com/users/673423",
"pm_score": 8,
"selected": false,
"text": "<p>Since Python 3.3, you can force the normal <code>print()</code> function to flush without the need to use <code>sys.stdout.flush()</code>; just set the \"flush\" keyword argument to true. From <a href=\"https://docs.python.org/3.3/library/functions.html#print\">the documentation</a>:</p>\n\n<blockquote>\n <p><strong>print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)</strong></p>\n \n <p>Print objects to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.</p>\n \n <p>All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.</p>\n \n <p>The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. <strong>Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 30682091,
"author": "kmario23",
"author_id": 2956066,
"author_profile": "https://Stackoverflow.com/users/2956066",
"pm_score": 3,
"selected": false,
"text": "<p>I did it like this in Python 3.4:</p>\n\n<pre><code>'''To write to screen in real-time'''\nmessage = lambda x: print(x, flush=True, end=\"\")\nmessage('I am flushing out now...')\n</code></pre>\n"
},
{
"answer_id": 33265549,
"author": "Noah Krasser",
"author_id": 5243630,
"author_profile": "https://Stackoverflow.com/users/5243630",
"pm_score": 6,
"selected": false,
"text": "<p>With Python 3.x the <code>print()</code> function has been extended:</p>\n\n<pre><code>print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)\n</code></pre>\n\n<p>So, you can just do:</p>\n\n<pre><code>print(\"Visiting toilet\", flush=True)\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://docs.python.org/3.3/library/functions.html?highlight=print#print\" rel=\"noreferrer\">Python Docs Entry</a></p>\n"
},
{
"answer_id": 35467658,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 8,
"selected": false,
"text": "<blockquote>\n<h1>How to flush output of Python print?</h1>\n</blockquote>\n<p>I suggest five ways of doing this:</p>\n<ul>\n<li>In Python 3, call <code>print(..., flush=True)</code> (the flush argument is not available in Python 2's print function, and there is no analogue for the print statement).</li>\n<li>Call <code>file.flush()</code> on the output file (we can wrap python 2's print function to do this), for example, <code>sys.stdout</code></li>\n<li>apply this to every print function call in the module with a partial function,<br />\n<code>print = partial(print, flush=True)</code> applied to the module global.</li>\n<li>apply this to the process with a flag (<code>-u</code>) passed to the interpreter command</li>\n<li>apply this to every python process in your environment with <code>PYTHONUNBUFFERED=TRUE</code> (and unset the variable to undo this).</li>\n</ul>\n<h2>Python 3.3+</h2>\n<p>Using Python 3.3 or higher, you can just provide <code>flush=True</code> as a keyword argument to the <code>print</code> function:</p>\n<pre><code>print('foo', flush=True) \n</code></pre>\n<h2>Python 2 (or < 3.3)</h2>\n<p>They did not backport the <code>flush</code> argument to Python 2.7 So if you're using Python 2 (or less than 3.3), and want code that's compatible with both 2 and 3, may I suggest the following compatibility code. (Note the <code>__future__</code> import must be at/very "near the <a href=\"https://docs.python.org/2/reference/simple_stmts.html#future-statements\" rel=\"noreferrer\">top of your module</a>"):</p>\n<pre><code>from __future__ import print_function\nimport sys\n\nif sys.version_info[:2] < (3, 3):\n old_print = print\n def print(*args, **kwargs):\n flush = kwargs.pop('flush', False)\n old_print(*args, **kwargs)\n if flush:\n file = kwargs.get('file', sys.stdout)\n # Why might file=None? IDK, but it works for print(i, file=None)\n file.flush() if file is not None else sys.stdout.flush()\n</code></pre>\n<p>The above compatibility code will cover most uses, but for a much more thorough treatment, <a href=\"https://bitbucket.org/gutworth/six/src/3deee854df8a5f1cc04dd721c18dee2128584f8c/six.py?at=default#six.py-721\" rel=\"noreferrer\">see the <code>six</code> module</a>.</p>\n<p>Alternatively, you can just call <code>file.flush()</code> after printing, for example, with the print statement in Python 2:</p>\n<pre><code>import sys\nprint 'delayed output'\nsys.stdout.flush()\n</code></pre>\n<h2>Changing the default in one module to <code>flush=True</code></h2>\n<p>You can change the default for the print function by using functools.partial on the global scope of a module:</p>\n<pre><code>import functools\nprint = functools.partial(print, flush=True)\n</code></pre>\n<p>if you look at our new partial function, at least in Python 3:</p>\n<pre><code>>>> print = functools.partial(print, flush=True)\n>>> print\nfunctools.partial(<built-in function print>, flush=True)\n</code></pre>\n<p>We can see it works just like normal:</p>\n<pre><code>>>> print('foo')\nfoo\n</code></pre>\n<p>And we can actually override the new default:</p>\n<pre><code>>>> print('foo', flush=False)\nfoo\n</code></pre>\n<p>Note again, this only changes the current global scope, because the print name on the current global scope will overshadow the builtin <code>print</code> function (or unreference the compatibility function, if using one in Python 2, in that current global scope).</p>\n<p>If you want to do this inside a function instead of on a module's global scope, you should give it a different name, e.g.:</p>\n<pre><code>def foo():\n printf = functools.partial(print, flush=True)\n printf('print stuff like this')\n</code></pre>\n<p>If you declare it a global in a function, you're changing it on the module's global namespace, so you should just put it in the global namespace, unless that specific behavior is exactly what you want.</p>\n<h2>Changing the default for the process</h2>\n<p>I think the best option here is to use the <code>-u</code> flag to get unbuffered output.</p>\n<pre><code>$ python -u script.py\n</code></pre>\n<p>or</p>\n<pre><code>$ python -um package.module\n</code></pre>\n<p>From the <a href=\"https://docs.python.org/2/using/cmdline.html#cmdoption-u\" rel=\"noreferrer\">docs</a>:</p>\n<blockquote>\n<p>Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.</p>\n<p>Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.</p>\n</blockquote>\n<h2>Changing the default for the shell operating environment</h2>\n<p>You can get this behavior for all python processes in the environment or environments that inherit from the environment if you set the environment variable to a nonempty string:</p>\n<p>e.g., in Linux or OSX:</p>\n<pre><code>$ export PYTHONUNBUFFERED=TRUE\n</code></pre>\n<p>or Windows:</p>\n<pre><code>C:\\SET PYTHONUNBUFFERED=TRUE\n</code></pre>\n<p>from the <a href=\"https://docs.python.org/2/using/cmdline.html#envvar-PYTHONUNBUFFERED\" rel=\"noreferrer\">docs</a>:</p>\n<blockquote>\n<p><strong>PYTHONUNBUFFERED</strong></p>\n<p>If this is set to a non-empty string it is equivalent to specifying the -u option.</p>\n</blockquote>\n<hr />\n<h2>Addendum</h2>\n<p>Here's the help on the print function from Python 2.7.12 - note that there is <em>no</em> <code>flush</code> argument:</p>\n<pre><code>>>> from __future__ import print_function\n>>> help(print)\nprint(...)\n print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n \n Prints the values to a stream, or to sys.stdout by default.\n Optional keyword arguments:\n file: a file-like object (stream); defaults to the current sys.stdout.\n sep: string inserted between values, default a space.\n end: string appended after the last value, default a newline.\n</code></pre>\n"
},
{
"answer_id": 37242598,
"author": "user263387",
"author_id": 6338046,
"author_profile": "https://Stackoverflow.com/users/6338046",
"pm_score": 4,
"selected": false,
"text": "<p>In Python 3 you can overwrite the <em>print</em> function with the default set to <code>flush = True</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>def print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=True):\n __builtins__.print(*objects, sep=sep, end=end, file=file, flush=flush)\n</code></pre>\n"
},
{
"answer_id": 58741275,
"author": "Guillaume Mougeot",
"author_id": 10759078,
"author_profile": "https://Stackoverflow.com/users/10759078",
"pm_score": 3,
"selected": false,
"text": "<p>I first struggled to understand how the flush option was working. I wanted to do a 'loading display' and here is the solution I found:</p>\n\n<pre><code>for i in range(100000):\n print('{:s}\\r'.format(''), end='', flush=True)\n print('Loading index: {:d}/100000'.format(i+1), end='')\n</code></pre>\n\n<p>The first line flushes the previous print and the second line prints a new updated message. I don't know if an one-line syntax exists here.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8835/"
] |
How do I force Python's `print` function to flush the buffered output to the screen?
|
In Python 3, [`print`](https://docs.python.org/library/functions.html#print) can take an optional `flush` argument:
```
print("Hello, World!", flush=True)
```
In Python 2, after calling `print`, do:
```
import sys
sys.stdout.flush()
```
By default, [`print`](https://docs.python.org/2/reference/simple_stmts.html#the-print-statement) prints to [`sys.stdout`](https://docs.python.org/2/library/sys.html#sys.stdout) (see the documentation for more about [file objects](https://docs.python.org/2/library/stdtypes.html#file-objects)).
|
230,788 |
<p>I need to select from a table and filter on dates greater than a
specified date. </p>
<p>The problem I'm having is that the dates are stored as nchar(20) and I
can't seem to get it converted to date in the where clause. </p>
<pre><code>SELECT CONVERT(DATETIME,log_time,20) from dbo.logs
where CONVERT(DATETIME,log_time,20) > '10/20/2008'
</code></pre>
<p>Msg 241, Level 16, State 1, Line 1
Conversion failed when converting datetime from character string. </p>
|
[
{
"answer_id": 230802,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>try this:</p>\n\n<pre><code>select convert(datetime, cast(trim(log_time), nvarchar)) from dbo.logs\nwhere convert(datetime, cast(trim(log_time), nvarchar)) > '10/20/2008'\n</code></pre>\n\n<p>I think the trick is that you need to trim the string and cast to nvarchar</p>\n"
},
{
"answer_id": 230814,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Msg 195, Level 15, State 10, Line 1\n'trim' is not a recognized built-in function name.</p>\n"
},
{
"answer_id": 230854,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>This should work.</p>\n\n<pre><code>select convert(datetime, cast(rtrim(log_time), nvarchar)) from dbo.logs\nwhere convert(datetime, cast(rtrim(log_time), nvarchar)) > '10/20/2008'\n</code></pre>\n"
},
{
"answer_id": 230879,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Msg 1035, Level 15, State 10, Line 1\nIncorrect syntax near 'cast', expected 'AS'.</p>\n"
},
{
"answer_id": 231440,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I talked to our SQL Server DBA. He said the problem was with bad data. He said on some the dates the m was left off of the am or pm. He wrote me a view where he handles the problem for me and now I can select from the view and the date is a datetime data type also.</p>\n\n<p>Thanks for everyone's help.</p>\n\n<p>Billy</p>\n"
},
{
"answer_id": 691350,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try </p>\n\n<p>select convert(datetime, cast(rtrim(log_time) AS nvarchar)) from dbo.logswhere convert(datetime, cast(rtrim(log_time) AS nvarchar)) > '10/20/2008'</p>\n\n<p>or simply</p>\n\n<p>select CAST(log_time AS DATETIME) from dbo.logs\nwhere CAST(log_time AS DATETIME) > '10/20/2008'</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to select from a table and filter on dates greater than a
specified date.
The problem I'm having is that the dates are stored as nchar(20) and I
can't seem to get it converted to date in the where clause.
```
SELECT CONVERT(DATETIME,log_time,20) from dbo.logs
where CONVERT(DATETIME,log_time,20) > '10/20/2008'
```
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting datetime from character string.
|
This should work.
```
select convert(datetime, cast(rtrim(log_time), nvarchar)) from dbo.logs
where convert(datetime, cast(rtrim(log_time), nvarchar)) > '10/20/2008'
```
|
230,790 |
<p>I find that most books concerning C++ templates don't tell anything about whether it's possible or not to use initialization list in constructor of a template class.</p>
<p>For example, I have code like this:</p>
<pre><code>template <class T>
class Stack {
T* data;
std::size_t count;
std::size_t capacity;
enum {INIT = 5};
public:
Stack() {
count = 0;
capacity = INIT;
data = new T [INIT];
}
</code></pre>
<p>Can I replace the constructor with</p>
<pre><code>Stack(): count(0), capacity(INIT), data(new T [INIT])
</code></pre>
|
[
{
"answer_id": 230806,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 3,
"selected": true,
"text": "<p>Yes. Did the compiler tell you otherwise?</p>\n"
},
{
"answer_id": 230836,
"author": "chester89",
"author_id": 28298,
"author_profile": "https://Stackoverflow.com/users/28298",
"pm_score": 0,
"selected": false,
"text": "<p>I've just tried and VS2008 says that it's OK, but it seems a little bit strange because some great authors don't do that (Eckel, for example, in his \"Thinking in C++\").</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
I find that most books concerning C++ templates don't tell anything about whether it's possible or not to use initialization list in constructor of a template class.
For example, I have code like this:
```
template <class T>
class Stack {
T* data;
std::size_t count;
std::size_t capacity;
enum {INIT = 5};
public:
Stack() {
count = 0;
capacity = INIT;
data = new T [INIT];
}
```
Can I replace the constructor with
```
Stack(): count(0), capacity(INIT), data(new T [INIT])
```
|
Yes. Did the compiler tell you otherwise?
|
230,796 |
<p>I'm creating a table that looks something like this.</p>
<pre><code>CREATE TABLE packages
(
productCode char(2)
, name nvarchar(100)
, ...
)
</code></pre>
<p>How do I make sure the productCode is always one of two values <code>XJ</code> or <code>XD</code>?</p>
|
[
{
"answer_id": 230819,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "<pre><code>ALTER TABLE packages\nADD CONSTRAINT constraintname CHECK (productCode in ('XJ', 'XD'))\n</code></pre>\n"
},
{
"answer_id": 230826,
"author": "Jon Grant",
"author_id": 18774,
"author_profile": "https://Stackoverflow.com/users/18774",
"pm_score": 3,
"selected": false,
"text": "<p>Either make it a <a href=\"http://en.wikipedia.org/wiki/Foreign_key\" rel=\"nofollow noreferrer\">foreign key</a> to a lookup table, or add a <a href=\"http://en.wikipedia.org/wiki/Check_constraint\" rel=\"nofollow noreferrer\">check constraint</a> to enforce it.</p>\n"
},
{
"answer_id": 230833,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 2,
"selected": false,
"text": "<pre><code>CREATE TABLE packages\n(\n productCode char(2)\n , name nvarchar(100) \n , ...\n ,CONSTRAINT productCode CHECK (productCode in ('XJ','XD') )\n)\n</code></pre>\n"
},
{
"answer_id": 231107,
"author": "Kasper",
"author_id": 23499,
"author_profile": "https://Stackoverflow.com/users/23499",
"pm_score": 1,
"selected": false,
"text": "<p>In this case it sounds like the valueset for ProductCode is pretty limited and that you don't expects it to grow in a foreseeable future, so I tend to agree with checkconstraint answers. However in most cases I would implement the foreign key solution as suggested by Mr. Grant as my customers has a nasty habit of changing their mind ( and the requirements as well ) about once a day. In that situation it is my expirence that the FK version is easier to maintain.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] |
I'm creating a table that looks something like this.
```
CREATE TABLE packages
(
productCode char(2)
, name nvarchar(100)
, ...
)
```
How do I make sure the productCode is always one of two values `XJ` or `XD`?
|
```
ALTER TABLE packages
ADD CONSTRAINT constraintname CHECK (productCode in ('XJ', 'XD'))
```
|
230,831 |
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Unbalanced_binary_tree.svg/251px-Unbalanced_binary_tree.svg.png" alt="alt text"></p>
<p>The image above is from <a href="http://en.wikipedia.org/wiki/AVL_tree" rel="nofollow noreferrer">"Wikipedia's entry on AVL trees"</a> which Wikipedia indicates is unbalanced.
How is this tree not balanced already?
Here's a quote from the article:</p>
<blockquote>
<p>The balance factor of a node is the height of its right subtree minus the height of its left subtree and a node with balance factor 1, 0, or -1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the subtrees.</p>
</blockquote>
<p>Both the left and right subtrees have a height of 4. The right subtree of the left tree has a height of 3 which is still only 1 less than 4. Can someone explain what I'm missing?</p>
|
[
{
"answer_id": 230841,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 4,
"selected": false,
"text": "<p>Node 76 is unbalanced, for example, because its right subtree is of height 0 and the left is of height 3.</p>\n"
},
{
"answer_id": 230843,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 2,
"selected": false,
"text": "<p>Intuitively, it's because it's not as small as possible. e.g., 12 should be the parent of 9 and 14. As it is, 9 has no left sub-tree so it's out of balance. A tree is a hierarchical data structure so a rule like \"balanced\" often apply to every node and not just the root node.</p>\n\n<p>You're correct the root node is balanced, but not all the nodes of the tree are.</p>\n"
},
{
"answer_id": 230966,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": true,
"text": "<p>To be balanced, every node in the tree must, either,</p>\n\n<ul>\n<li>have no children, (be a \"leaf\" node)</li>\n<li>Have two children.</li>\n<li><p>Or, if it has only one child, that child must be a leaf.</p>\n\n<p>In the chart you posted, 9, 54 & 76 violate the last rule.</p></li>\n</ul>\n\n<p>Properly balanced, the tree would look like:</p>\n\n<pre><code>Root: 23\n(23) -> 14 & 67\n(14) -> 12 & 17\n(12) -> 9\n(17) -> 19\n(67) -> 50 & 72\n(50) -> 54\n(72) -> 76\n</code></pre>\n\n<p>UPDATE: (after almost 9 years, I created a cool online chart for the graph at <a href=\"https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=SO_Balanced_AVL_Tree%20.xml#Uhttps%3A%2F%2Fraw.githubusercontent.com%2Fjamescurran%2FHonestIllusion%2Fmaster%2FSO_Balanced_AVL_Tree%2520.xml\" rel=\"nofollow noreferrer\">draw.io</a>)<a href=\"https://i.stack.imgur.com/n6KwW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n6KwW.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 23232436,
"author": "par",
"author_id": 312594,
"author_profile": "https://Stackoverflow.com/users/312594",
"pm_score": 2,
"selected": false,
"text": "<p>Another way to look at this is that the height <code>h</code> of any node is given by:</p>\n\n<p><code>h = 1 + max( left.height, right.height )</code></p>\n\n<p>and a node is unbalanced whenever:</p>\n\n<p><code>abs( left.height - right.height ) > 1</code></p>\n\n<p>Looking at the tree above:</p>\n\n<pre><code>- Node 12 is a leaf node so its height = 1+max(0,0) = 1\n- Node 14 has one child (12, on the left), so its height is = 1+max(1,0) = 2\n- Node 9 has one child (14, on the right), so its height is = 1+max(0,2) = 3\n</code></pre>\n\n<p>To determine if node 9 is balanced or not we look at the height of its children:</p>\n\n<pre><code>- 9's left child is NULL, so 9.left.height = 0\n- 9's right child (14) has height 2, so 9.right.height = 2\n</code></pre>\n\n<p>Now solve to show that node 9 is unbalanced:</p>\n\n<pre><code>9.unbalanced = abs( 9.left.height - 9.right.height ) > 1\n9.unbalanced = abs( 0 - 2 ) > 1\n9.unbalanced = abs( -2 ) > 1\n9.unbalanced = 2 > 1\n9.unbalanced = true\n</code></pre>\n\n<p>Similar calculations can be made for every other node.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/412/"
] |

The image above is from ["Wikipedia's entry on AVL trees"](http://en.wikipedia.org/wiki/AVL_tree) which Wikipedia indicates is unbalanced.
How is this tree not balanced already?
Here's a quote from the article:
>
> The balance factor of a node is the height of its right subtree minus the height of its left subtree and a node with balance factor 1, 0, or -1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the subtrees.
>
>
>
Both the left and right subtrees have a height of 4. The right subtree of the left tree has a height of 3 which is still only 1 less than 4. Can someone explain what I'm missing?
|
To be balanced, every node in the tree must, either,
* have no children, (be a "leaf" node)
* Have two children.
* Or, if it has only one child, that child must be a leaf.
In the chart you posted, 9, 54 & 76 violate the last rule.
Properly balanced, the tree would look like:
```
Root: 23
(23) -> 14 & 67
(14) -> 12 & 17
(12) -> 9
(17) -> 19
(67) -> 50 & 72
(50) -> 54
(72) -> 76
```
UPDATE: (after almost 9 years, I created a cool online chart for the graph at [draw.io](https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=SO_Balanced_AVL_Tree%20.xml#Uhttps%3A%2F%2Fraw.githubusercontent.com%2Fjamescurran%2FHonestIllusion%2Fmaster%2FSO_Balanced_AVL_Tree%2520.xml))[](https://i.stack.imgur.com/n6KwW.png)
|
230,834 |
<p>This is a winforms application.</p>
<p>In windows, I want the user to click and button, and then a popup should make the user select the path of where they want to save the file.</p>
|
[
{
"answer_id": 230867,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": "<p><code>StringBuilder.ToString()</code> can be passed to the <code>TextStream.Write()</code> method after creating the file.</p>\n\n<p>Using the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog(VS.80).aspx\" rel=\"nofollow noreferrer\">SaveFileDialog class</a>, you can let the user select path and file name - in a standard way. Detailed examples in the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog(VS.80).aspx\" rel=\"nofollow noreferrer\">doc</a>.</p>\n"
},
{
"answer_id": 230874,
"author": "Jon Grant",
"author_id": 18774,
"author_profile": "https://Stackoverflow.com/users/18774",
"pm_score": 5,
"selected": false,
"text": "<p>You want the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx\" rel=\"noreferrer\">WriteAllText</a> function.</p>\n\n<pre><code>using (SaveFileDialog dialog = new SaveFileDialog()) {\n if (dialog.ShowDialog(this) == DialogResult.OK) {\n File.WriteAllText(dialog.FileName, yourStringBuilder.ToString());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 230880,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/4b1063zt.aspx\" rel=\"nofollow noreferrer\">StringBuilder.ToString()</a> will get you the string.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx\" rel=\"nofollow noreferrer\">This link</a> will show you how to write text to a file.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.aspx\" rel=\"nofollow noreferrer\">This link</a> will show you how to call SaveFileDialog and pass a stream to it to save.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 230910,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 2,
"selected": false,
"text": "<p>Think no longer...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication2 {\npublic partial class Form1 : Form {\n\n StringBuilder sb = new StringBuilder();\n\n public Form1() {\n InitializeComponent();\n\n sb.Append(\"This is going \");\n sb.Append(\"to be saved to a text file\");\n }\n\n private void button1_Click(object sender, EventArgs e) {\n using (SaveFileDialog dlg = new SaveFileDialog()) {\n if (dlg.ShowDialog() == DialogResult.OK) {\n string fileName = dlg.FileName;\n SaveToFile(fileName);\n }\n }\n }\n\n private void SaveToFile(string fileName) {\n System.IO.TextWriter w = new System.IO.StreamWriter(fileName);\n w.Write(sb.ToString());\n w.Flush();\n w.Close();\n }\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This is a winforms application.
In windows, I want the user to click and button, and then a popup should make the user select the path of where they want to save the file.
|
You want the [WriteAllText](http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx) function.
```
using (SaveFileDialog dialog = new SaveFileDialog()) {
if (dialog.ShowDialog(this) == DialogResult.OK) {
File.WriteAllText(dialog.FileName, yourStringBuilder.ToString());
}
}
```
|
230,842 |
<p>The first one is definitely something that works, but which one below is the efficient way?</p>
<pre><code>switch($type) {
case 1:
print 'success';
break;
case 2:
print 'success';
break;
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
</code></pre>
<p>Since 1, 2 and 3 print do the same, can I do this?</p>
<pre><code>switch($type) {
case 1, 2, 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
</code></pre>
<p>or</p>
<pre><code>switch($type) {
case 1:
case 2:
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
</code></pre>
|
[
{
"answer_id": 230857,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 5,
"selected": true,
"text": "<pre><code> switch($type) \n {\n case 1:\n case 2:\n case 3:\n print 'success';\n break;\n case 4:\n print 'success for type 4';\n break;\n }\n</code></pre>\n\n<p>Is the way to go!</p>\n"
},
{
"answer_id": 230858,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": false,
"text": "<p>PHP manual lists an example like your 3rd for <a href=\"http://us3.php.net/manual/en/control-structures.switch.php\" rel=\"nofollow noreferrer\">switch</a>:</p>\n\n<pre><code><?php\nswitch ($i) {\ncase 0:\ncase 1:\ncase 2:\n echo \"i is less than 3 but not negative\";\n break;\ncase 3:\n echo \"i is 3\";\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 231651,
"author": "null",
"author_id": 25411,
"author_profile": "https://Stackoverflow.com/users/25411",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with the others on the usage of:</p>\n\n<pre><code>switch ($i) {\n case 0: //drop\n case 1: //drop\n case 2: //drop\n echo \"i is 0, 1, or 2\";\n break;\n // or you can line them up like this.\n case 3: case 4: case 5:\n echo \"i is 3, 4 or 5\";\n break;\n}\n</code></pre>\n\n<p>The only thing I would add is the comments for the multi-line drop through case statements, so that way you know it's not a bug when you (or someone else) looks at the code after it was initially written.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
The first one is definitely something that works, but which one below is the efficient way?
```
switch($type) {
case 1:
print 'success';
break;
case 2:
print 'success';
break;
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
```
Since 1, 2 and 3 print do the same, can I do this?
```
switch($type) {
case 1, 2, 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
```
or
```
switch($type) {
case 1:
case 2:
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
```
|
```
switch($type)
{
case 1:
case 2:
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
```
Is the way to go!
|
230,845 |
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p>
<pre><code>import commands
commands.getoutput('server stop')
</code></pre>
|
[
{
"answer_id": 230855,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 0,
"selected": false,
"text": "<p>Should be able to pass it as a parameter. something like:</p>\n\n<pre><code>commands.getoutput('server stop -p password')\n</code></pre>\n"
},
{
"answer_id": 230862,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 3,
"selected": false,
"text": "<p>Use <a href=\"http://www.python.org/doc/2.5.2/lib/module-subprocess.html\" rel=\"nofollow noreferrer\">subprocess</a>. Call Popen() to create your process and use communicate() to send it text. Sorry, forgot to include the PIPE..</p>\n\n<pre><code>from subprocess import Popen, PIPE\n\nproc = Popen(['server', 'stop'], stdin=PIPE)\n\nproc.communicate('password')\n</code></pre>\n\n<p>You would do better do avoid the password and try a scheme like sudo and sudoers. Pexpect, mentioned elsewhere, is not part of the standard library.</p>\n"
},
{
"answer_id": 230982,
"author": "darrickc",
"author_id": 7949,
"author_profile": "https://Stackoverflow.com/users/7949",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to work better:</p>\n\n<pre><code>import popen2\n\n(stdout, stdin) = popen2.popen2('server stop')\n\nstdin.write(\"password\")\n</code></pre>\n\n<p>But it's not 100% yet. Even though \"password\" is the correct password I'm still getting su: Sorry back from the csh script when it's trying to su to root.</p>\n"
},
{
"answer_id": 230986,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 4,
"selected": true,
"text": "<p>Have a look at the <a href=\"http://www.noah.org/wiki/Pexpect\" rel=\"noreferrer\">pexpect</a> module. It is designed to deal with interactive programs, which seems to be your case.</p>\n\n<p>Oh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D</p>\n"
},
{
"answer_id": 234301,
"author": "darrickc",
"author_id": 7949,
"author_profile": "https://Stackoverflow.com/users/7949",
"pm_score": 0,
"selected": false,
"text": "<p>To avoid having to answer the Password question in the python script I'm just going to run the script as root. This question is still unanswered but I guess I'll just do it this way for now.</p>\n"
},
{
"answer_id": 321950,
"author": "darrickc",
"author_id": 7949,
"author_profile": "https://Stackoverflow.com/users/7949",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import pexpect\nchild = pexpect.spawn('server stop')\nchild.expect_exact('Password:')\n\nchild.sendline('password')\n\nprint \"Stopping the servers...\"\n\nindex = child.expect_exact(['Server processes successfully stopped.', 'Server is not running...'], 60)\nchild.expect(pexpect.EOF)\n</code></pre>\n\n<p>Did the trick! Pexpect rules!</p>\n"
},
{
"answer_id": 809168,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Add <code>input=</code> in <code>proc.communicate()</code> make it run, for guys who like to use standard lib.</p>\n\n<pre><code>from subprocess import Popen, PIPE\nproc = Popen(['server', 'stop'], stdin=PIPE)\nproc.communicate(input='password')\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7949/"
] |
I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:
```
import commands
commands.getoutput('server stop')
```
|
Have a look at the [pexpect](http://www.noah.org/wiki/Pexpect) module. It is designed to deal with interactive programs, which seems to be your case.
Oh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D
|
230,886 |
<p>I've seen this format used for comma-delimited lists in some C++ code (although this could apply to any language):</p>
<pre><code>void function( int a
, int b
, int c
)
</code></pre>
<p>I was wondering why would someone use that over a more common format such as:</p>
<pre><code>void function (int a,
int b,
int c
)
</code></pre>
|
[
{
"answer_id": 230895,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 2,
"selected": false,
"text": "<p>It is easier to add a parameter at the end starting by duplicating previous parameter (line).</p>\n\n<p>Make sense when you are sure that first parameter will never change, which is often the case.</p>\n"
},
{
"answer_id": 230901,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 1,
"selected": false,
"text": "<p>The only benefit I would see, is when you add a parameter, you just have to copy and paste the last line, saving you the extra couple key strokes of editing comma position and such. </p>\n"
},
{
"answer_id": 230904,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 2,
"selected": false,
"text": "<p>Malice?</p>\n\n<p>Seriously though, it's hard to account for formatting style sometimes. It's largely a matter of personal taste. Personally, I think that <em>both</em> forms are a little nasty unless you're seriously restricted in terms of line-length.</p>\n"
},
{
"answer_id": 230905,
"author": "osp70",
"author_id": 2357,
"author_profile": "https://Stackoverflow.com/users/2357",
"pm_score": 0,
"selected": false,
"text": "<p>I know when I wrap and's in a sql or if statement I try to make sure the and is the start of the next line. </p>\n\n<p>If A and B <br>\nand C </p>\n\n<p>I think it makes it clear the the C is still part of the if. The first format you show may be that. But as with most style questions the simple matter is that if the team decides on one style then it should be adhered to.</p>\n"
},
{
"answer_id": 230906,
"author": "Pradeep",
"author_id": 29693,
"author_profile": "https://Stackoverflow.com/users/29693",
"pm_score": 1,
"selected": false,
"text": "<p>Seems to me like a personal choice.</p>\n"
},
{
"answer_id": 230915,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 1,
"selected": false,
"text": "<p>When scanning the file quicky, it's clear that each line that begins with a comma is a continuation of the line above it (compared to a line that's simply indented further than the one above). It's a generalization of the following style:</p>\n\n<pre><code>std::cout << \"some info \"\n << \"some more info \" << 4\n + 5 << std::endl;\n</code></pre>\n\n<p>(Please note, in this case, breaking up 4 + 5 is stupid, but if you have a complex math statement it may be necessary).</p>\n\n<p>I use this a lot, especially when dealing with conditionals such as if, for, and while statements. Because it's also common for one-line conditionals to omit the curlies.</p>\n\n<pre><code> std::vector<int> v = ...;\n std::vector<int> w = ...;\n for (std::vector<int>::iterator i = v.begin()\n , std::vector<int>::iterator j = w.begin()\n ; i != v.end() && j != w.end()\n ; ++i, ++j)\n std::cout << *i + *j << std::endl;\n</code></pre>\n"
},
{
"answer_id": 230922,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 5,
"selected": true,
"text": "<p>That's a pretty common coding style when writing SQL statements:</p>\n\n<pre><code>SELECT field1\n , field2\n , field3\n-- , field4\n , field5\nFROM tablename\n</code></pre>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Lets you add, remove, or rearrange fields easily without having to worry about that final trailing comma.</li>\n<li>Lets you easily comment out a row (TSQL uses \"--\") without messing up the rest of the statement.</li>\n</ul>\n\n<p>I wouldn't think you'd want to rearrange parameter order in a function as frequent as you do in SQL, so maybe its just somebody's habit.</p>\n\n<p>The ability to comment one of them out will depend on the specific language being used. Not sure about C++. I know that VB.Net wouldn't allow it, but that's because it requires a continuation character ( _ ) to split statements across lines.</p>\n"
},
{
"answer_id": 230926,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 1,
"selected": false,
"text": "<p>No reason, I suspect it's just a matter of personal preference.</p>\n\n<p>I'd personally prefer the second one.</p>\n\n<pre><code>void function (int a,\n int b,\n int c\n )\n</code></pre>\n"
},
{
"answer_id": 230934,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Another advantage is that in the first example you could comment-out either the B or C lines, and it will stay syntactically correct. In the second example, if you tried to comment out the C line, you'd have a syntax error.</p>\n\n<p>Not really worth making it that ugly, if you ask me.</p>\n"
},
{
"answer_id": 230935,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>The only benefit I would see, is when you add a parameter, you just have to copy and paste the last line, saving you the extra couple key strokes of editing comma position and such.</p>\n</blockquote>\n\n<p>The same goes for if you are removing the last parameter.</p>\n"
},
{
"answer_id": 231322,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 1,
"selected": false,
"text": "<p>When you add another field to the end, the single line you add contains the new comma, producing a diff of a single line addition, making it slightly easier to see what has changed when viewing change logs some time in the future. </p>\n"
},
{
"answer_id": 237945,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "<p>It seems like most of the answers center around the ability to comment out or add new parameters easily. But it seems that you get the same effect with putting the comma at the end of the line rather than the beginning:</p>\n\n<pre><code>function(\n int a,\n int b,\n// int c,\n int d\n )\n</code></pre>\n\n<p>You might say that you can't do that to the last parameter, and you would be right, but with the other form, you can't do it to the first parameter:</p>\n\n<pre><code>function (\n// int a\n , int b\n , int c\n , int d\n )\n</code></pre>\n\n<p>So the tradeoff is being able to comment out the first parameter vs. being able to comment out the last parameter + being able to add new parameters without adding a comma to the previous last parameter.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] |
I've seen this format used for comma-delimited lists in some C++ code (although this could apply to any language):
```
void function( int a
, int b
, int c
)
```
I was wondering why would someone use that over a more common format such as:
```
void function (int a,
int b,
int c
)
```
|
That's a pretty common coding style when writing SQL statements:
```
SELECT field1
, field2
, field3
-- , field4
, field5
FROM tablename
```
Advantages:
* Lets you add, remove, or rearrange fields easily without having to worry about that final trailing comma.
* Lets you easily comment out a row (TSQL uses "--") without messing up the rest of the statement.
I wouldn't think you'd want to rearrange parameter order in a function as frequent as you do in SQL, so maybe its just somebody's habit.
The ability to comment one of them out will depend on the specific language being used. Not sure about C++. I know that VB.Net wouldn't allow it, but that's because it requires a continuation character ( \_ ) to split statements across lines.
|
230,892 |
<p>I have quickly read (and will read with more care soon) the article of Scott Allen concerning the possibility to use an other provider of the default SQL Express or SQL Server database to use the "<a href="http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx" rel="nofollow noreferrer">Membership and Role Providers</a>" for ASP.NET.</p>
<p>We will soon need to open a part of our project to some client via the web and I thought about using the "<a href="http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx" rel="nofollow noreferrer">Membership and Role Providers</a>" but our database is PostGreSql. </p>
<p>Does any one have some experience with "<a href="http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx" rel="nofollow noreferrer">Membership and Role Providers</a> and an other database type (not SQL Server)? Is it worth it or it's a pain?</p>
|
[
{
"answer_id": 230895,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 2,
"selected": false,
"text": "<p>It is easier to add a parameter at the end starting by duplicating previous parameter (line).</p>\n\n<p>Make sense when you are sure that first parameter will never change, which is often the case.</p>\n"
},
{
"answer_id": 230901,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 1,
"selected": false,
"text": "<p>The only benefit I would see, is when you add a parameter, you just have to copy and paste the last line, saving you the extra couple key strokes of editing comma position and such. </p>\n"
},
{
"answer_id": 230904,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 2,
"selected": false,
"text": "<p>Malice?</p>\n\n<p>Seriously though, it's hard to account for formatting style sometimes. It's largely a matter of personal taste. Personally, I think that <em>both</em> forms are a little nasty unless you're seriously restricted in terms of line-length.</p>\n"
},
{
"answer_id": 230905,
"author": "osp70",
"author_id": 2357,
"author_profile": "https://Stackoverflow.com/users/2357",
"pm_score": 0,
"selected": false,
"text": "<p>I know when I wrap and's in a sql or if statement I try to make sure the and is the start of the next line. </p>\n\n<p>If A and B <br>\nand C </p>\n\n<p>I think it makes it clear the the C is still part of the if. The first format you show may be that. But as with most style questions the simple matter is that if the team decides on one style then it should be adhered to.</p>\n"
},
{
"answer_id": 230906,
"author": "Pradeep",
"author_id": 29693,
"author_profile": "https://Stackoverflow.com/users/29693",
"pm_score": 1,
"selected": false,
"text": "<p>Seems to me like a personal choice.</p>\n"
},
{
"answer_id": 230915,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 1,
"selected": false,
"text": "<p>When scanning the file quicky, it's clear that each line that begins with a comma is a continuation of the line above it (compared to a line that's simply indented further than the one above). It's a generalization of the following style:</p>\n\n<pre><code>std::cout << \"some info \"\n << \"some more info \" << 4\n + 5 << std::endl;\n</code></pre>\n\n<p>(Please note, in this case, breaking up 4 + 5 is stupid, but if you have a complex math statement it may be necessary).</p>\n\n<p>I use this a lot, especially when dealing with conditionals such as if, for, and while statements. Because it's also common for one-line conditionals to omit the curlies.</p>\n\n<pre><code> std::vector<int> v = ...;\n std::vector<int> w = ...;\n for (std::vector<int>::iterator i = v.begin()\n , std::vector<int>::iterator j = w.begin()\n ; i != v.end() && j != w.end()\n ; ++i, ++j)\n std::cout << *i + *j << std::endl;\n</code></pre>\n"
},
{
"answer_id": 230922,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 5,
"selected": true,
"text": "<p>That's a pretty common coding style when writing SQL statements:</p>\n\n<pre><code>SELECT field1\n , field2\n , field3\n-- , field4\n , field5\nFROM tablename\n</code></pre>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Lets you add, remove, or rearrange fields easily without having to worry about that final trailing comma.</li>\n<li>Lets you easily comment out a row (TSQL uses \"--\") without messing up the rest of the statement.</li>\n</ul>\n\n<p>I wouldn't think you'd want to rearrange parameter order in a function as frequent as you do in SQL, so maybe its just somebody's habit.</p>\n\n<p>The ability to comment one of them out will depend on the specific language being used. Not sure about C++. I know that VB.Net wouldn't allow it, but that's because it requires a continuation character ( _ ) to split statements across lines.</p>\n"
},
{
"answer_id": 230926,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 1,
"selected": false,
"text": "<p>No reason, I suspect it's just a matter of personal preference.</p>\n\n<p>I'd personally prefer the second one.</p>\n\n<pre><code>void function (int a,\n int b,\n int c\n )\n</code></pre>\n"
},
{
"answer_id": 230934,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Another advantage is that in the first example you could comment-out either the B or C lines, and it will stay syntactically correct. In the second example, if you tried to comment out the C line, you'd have a syntax error.</p>\n\n<p>Not really worth making it that ugly, if you ask me.</p>\n"
},
{
"answer_id": 230935,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>The only benefit I would see, is when you add a parameter, you just have to copy and paste the last line, saving you the extra couple key strokes of editing comma position and such.</p>\n</blockquote>\n\n<p>The same goes for if you are removing the last parameter.</p>\n"
},
{
"answer_id": 231322,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 1,
"selected": false,
"text": "<p>When you add another field to the end, the single line you add contains the new comma, producing a diff of a single line addition, making it slightly easier to see what has changed when viewing change logs some time in the future. </p>\n"
},
{
"answer_id": 237945,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "<p>It seems like most of the answers center around the ability to comment out or add new parameters easily. But it seems that you get the same effect with putting the comma at the end of the line rather than the beginning:</p>\n\n<pre><code>function(\n int a,\n int b,\n// int c,\n int d\n )\n</code></pre>\n\n<p>You might say that you can't do that to the last parameter, and you would be right, but with the other form, you can't do it to the first parameter:</p>\n\n<pre><code>function (\n// int a\n , int b\n , int c\n , int d\n )\n</code></pre>\n\n<p>So the tradeoff is being able to comment out the first parameter vs. being able to comment out the last parameter + being able to add new parameters without adding a comma to the previous last parameter.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
I have quickly read (and will read with more care soon) the article of Scott Allen concerning the possibility to use an other provider of the default SQL Express or SQL Server database to use the "[Membership and Role Providers](http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx)" for ASP.NET.
We will soon need to open a part of our project to some client via the web and I thought about using the "[Membership and Role Providers](http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx)" but our database is PostGreSql.
Does any one have some experience with "[Membership and Role Providers](http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx) and an other database type (not SQL Server)? Is it worth it or it's a pain?
|
That's a pretty common coding style when writing SQL statements:
```
SELECT field1
, field2
, field3
-- , field4
, field5
FROM tablename
```
Advantages:
* Lets you add, remove, or rearrange fields easily without having to worry about that final trailing comma.
* Lets you easily comment out a row (TSQL uses "--") without messing up the rest of the statement.
I wouldn't think you'd want to rearrange parameter order in a function as frequent as you do in SQL, so maybe its just somebody's habit.
The ability to comment one of them out will depend on the specific language being used. Not sure about C++. I know that VB.Net wouldn't allow it, but that's because it requires a continuation character ( \_ ) to split statements across lines.
|
230,893 |
<p>What is the fastest way to load data from flatfiles into a MySQL database, and then create the relations between the tables via foreign keys? </p>
<p>For example... I have a flat file in the format: </p>
<pre><code>[INDIVIDUAL] [POP] [MARKER] [GENOTYPE]
"INDIVIDUAL1", "CEU", "rs55555","AA"
"INDIVIDUAL1", "CEU", "rs535454","GA"
"INDIVIDUAL1", "CEU", "rs555566","AT"
"INDIVIDUAL1", "CEU", "rs12345","TT"
...
"INDIVIDUAL2", "JPT", "rs55555","AT"
</code></pre>
<p>Which I need to load into four tables:</p>
<pre><code>IND (id,fk_pop,name)
POP (id,population)
MARKER (id,rsid)
GENOTYPE (id,fk_ind,fk_rsid,call)
</code></pre>
<p>Specifically, how does one populate the foreign keys in a way that scales? The figures are in the range of 1000+ individuals, each with 1 million+ genotypes.</p>
|
[
{
"answer_id": 230913,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 3,
"selected": false,
"text": "<p>I would take a multiple step approach to do this.</p>\n\n<ol>\n<li>Load the data into a temporary table, that is matching the file format that you have</li>\n<li>Write queries to do the other inserts, starting the the general tables, then doing joins to get the FK values.</li>\n</ol>\n"
},
{
"answer_id": 255667,
"author": "Osama Al-Maadeed",
"author_id": 25544,
"author_profile": "https://Stackoverflow.com/users/25544",
"pm_score": 0,
"selected": false,
"text": "<p>You could to start with the base tables without foreign keys. You would then lookup the IDs as you insert data in the other tables.</p>\n\n<p>Another idea is that you could replace the IDs in the flat file(INDIVIDUAL1,CEU, ...etc.) by GUIDs . and then use them directly as IDs and foreign keys (i noticed this is tagged performance, this may not give the best \"performance\").</p>\n"
},
{
"answer_id": 449373,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>There is a simpler way.</p>\n\n<p>First, make sure you have a UNIQUE constraint on those columns that should have one (name, population, rsid).</p>\n\n<p>Then use something like the following:</p>\n\n<pre><code> LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE POP FIELDS TERMINATED BY ','\n ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES \n (@name, population, @rsid, @call);\n LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE MARKER FIELDS TERMINATED BY ',' \n ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES \n (@name, @population, rsid, @call);\n LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE IND FIELDS TERMINATED BY ',' \n ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES \n (name, @population, @rsid, @call) \n SET fk_pop = (SELECT id FROM POP WHERE population = @population);\n LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE GENOTYPE FIELDS TERMINATED BY ',' \n ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES \n (@name, @population, @rsid, call)\n SET fk_ind = (SELECT id FROM IND where name = @name),\n fk_rsid = (SELECT id FROM MARKER where rsid = @rsid);\n</code></pre>\n\n<p>Note where the @ is used to indicate variables, rather than column names. In the first 2 LOAD DATAs, these are just used to ignore data. In the second 2, they are used to look up the foreign keys.</p>\n\n<p>Might not be very fast, mind :).</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30911/"
] |
What is the fastest way to load data from flatfiles into a MySQL database, and then create the relations between the tables via foreign keys?
For example... I have a flat file in the format:
```
[INDIVIDUAL] [POP] [MARKER] [GENOTYPE]
"INDIVIDUAL1", "CEU", "rs55555","AA"
"INDIVIDUAL1", "CEU", "rs535454","GA"
"INDIVIDUAL1", "CEU", "rs555566","AT"
"INDIVIDUAL1", "CEU", "rs12345","TT"
...
"INDIVIDUAL2", "JPT", "rs55555","AT"
```
Which I need to load into four tables:
```
IND (id,fk_pop,name)
POP (id,population)
MARKER (id,rsid)
GENOTYPE (id,fk_ind,fk_rsid,call)
```
Specifically, how does one populate the foreign keys in a way that scales? The figures are in the range of 1000+ individuals, each with 1 million+ genotypes.
|
There is a simpler way.
First, make sure you have a UNIQUE constraint on those columns that should have one (name, population, rsid).
Then use something like the following:
```
LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE POP FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES
(@name, population, @rsid, @call);
LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE MARKER FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES
(@name, @population, rsid, @call);
LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE IND FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES
(name, @population, @rsid, @call)
SET fk_pop = (SELECT id FROM POP WHERE population = @population);
LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE GENOTYPE FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES
(@name, @population, @rsid, call)
SET fk_ind = (SELECT id FROM IND where name = @name),
fk_rsid = (SELECT id FROM MARKER where rsid = @rsid);
```
Note where the @ is used to indicate variables, rather than column names. In the first 2 LOAD DATAs, these are just used to ignore data. In the second 2, they are used to look up the foreign keys.
Might not be very fast, mind :).
|
230,896 |
<p>I have a list of variable names, like this:</p>
<pre><code>['foo', 'bar', 'baz']
</code></pre>
<p>(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)</p>
<p>How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables?</p>
<pre><code>{'foo': foo, 'bar': bar, 'baz': baz}
</code></pre>
<p>Now that I'm re-asking the question, I came up with:</p>
<pre><code>d = {}
for name in list_of_variable_names:
d[name] = eval(name)
</code></pre>
<p>Can that be improved upon?</p>
<p><strong>Update</strong>, responding to the question (in a comment) of why I'd want to do this:</p>
<p>I often find myself using the % operator to strings with a dictionary of names and values to interpolate. Often the names in the string is just the names of local variables. So (with the answer below) I can do something like this:</p>
<pre><code>message = '''Name: %(name)s
ZIP: %(zip)s
Dear %(name)s,
...''' % dict((x, locals()[x]) for x in ['name', 'zip'])
</code></pre>
|
[
{
"answer_id": 230907,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>Your original list <code>[foo, bar, baz]</code> doesn't contain the variable <em>names</em>, it just contains elements that refer to the same <em>values</em> as the variables you listed. This is because you can have two different variable names that refer to the same value.</p>\n\n<p>So, the list by itself doesn't contain information about what other names refer to the objects. The first element in your array has the name <code>foo</code> but it also has the name <code>a[0]</code> (assuming your array is called <code>a</code>). After executing the following code, <code>quux</code> also refers to the same object:</p>\n\n<pre><code>quux = a[0]\n</code></pre>\n\n<p>Update: You're right that you can use <code>eval()</code> for that, but its use is generally discouraged. Python provides a special member named <a href=\"http://www.python.org/doc/1.5.2p2/lib/typesother.html\" rel=\"nofollow noreferrer\"><code>__dict__</code></a> that contains the symbol table for the current module. So you can:</p>\n\n<pre><code>import __main__\nd = dict((x, __main__.__dict__[x]) for x in list_of_variable_names)\n</code></pre>\n\n<p>Having to <code>import __main__</code> when your code is in the unnamed main module is a quirk of Python.</p>\n"
},
{
"answer_id": 230955,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 3,
"selected": false,
"text": "<p>You can use list or generator comprehensions to build a list of key, value tuples used to directly instantiate a dict. The best way is below:</p>\n\n<pre><code>dict((name, eval(name)) for name in list_of_variable_names)\n</code></pre>\n\n<p>In addition, if you know, for example, that the variables exist in the local symbol table you can save yourself from the dangerous eval by looking the variable directly from locals:</p>\n\n<pre><code>dict((name, locals()[name]) for name in list_of_variable_names)\n</code></pre>\n\n<p>After your final update, I think the answer below is really what you want. If you're just using this for string expansion with strings that you control, just pass locals() directly to the string expansion and it will cherry-pick out the desired values</p>\n\n<p>If, however, these strings could ever come from an outside source (e.g. translation files), than it's a good idea to filter locals()</p>\n"
},
{
"answer_id": 230976,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 1,
"selected": false,
"text": "<p>Not efficient, but without invoking <code>eval</code>:</p>\n\n<pre><code>dict((k,v) for (k,v) in globals().iteritems() if k in list_of_variable_names)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>dict((k,v) for (k,v) in vars().iteritems() if k in list_of_variable_names)\n</code></pre>\n\n<p>depending on what you want.</p>\n"
},
{
"answer_id": 231368,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>Forget filtering <code>locals()</code>! The dictionary you give to the formatting string is allowed to contain unused keys:</p>\n\n<pre><code>>>> name = 'foo'\n>>> zip = 123\n>>> unused = 'whoops!'\n>>> locals()\n{'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...}\n>>> '%(name)s %(zip)i' % locals()\n'foo 123'\n</code></pre>\n\n<p>With the new <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\">f-string feature</a> in Python 3.6, using <code>locals()</code> is no longer necessary:</p>\n\n<pre><code>>>> name = 'foo'\n>>> zip = 123\n>>> unused = 'whoops!'\n>>> f'{zip: >5} {name.upper()}'\n' 123 FOO'\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
I have a list of variable names, like this:
```
['foo', 'bar', 'baz']
```
(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)
How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables?
```
{'foo': foo, 'bar': bar, 'baz': baz}
```
Now that I'm re-asking the question, I came up with:
```
d = {}
for name in list_of_variable_names:
d[name] = eval(name)
```
Can that be improved upon?
**Update**, responding to the question (in a comment) of why I'd want to do this:
I often find myself using the % operator to strings with a dictionary of names and values to interpolate. Often the names in the string is just the names of local variables. So (with the answer below) I can do something like this:
```
message = '''Name: %(name)s
ZIP: %(zip)s
Dear %(name)s,
...''' % dict((x, locals()[x]) for x in ['name', 'zip'])
```
|
Forget filtering `locals()`! The dictionary you give to the formatting string is allowed to contain unused keys:
```
>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> locals()
{'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...}
>>> '%(name)s %(zip)i' % locals()
'foo 123'
```
With the new [f-string feature](https://www.python.org/dev/peps/pep-0498/) in Python 3.6, using `locals()` is no longer necessary:
```
>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> f'{zip: >5} {name.upper()}'
' 123 FOO'
```
|
230,927 |
<p>I'm looking for best practices for establishing connections between Oracle 8 and Visual Studio 2005 applications. The target would be a Windows Forms application written in C# that hits the database once a second to monitor tables looking for their last inserted record. I'm considering using "Application settings" to store the connection string there, but I'd love to hear from you guys. Thanks in advance!</p>
<p>This is a very rudimentary draft:</p>
<pre><code>using System.Data;
using System.Data.OracleClient;
try
{
StringBuilder str = new StringBuilder();
string ora = Properties.Settings.Default.OracleConnectionString;
OracleConnection con = new OracleConnection(ora);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT timestamp FROM jde_out WHERE rownum = 1";
cmd.CommandType = CommandType.Text;
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
rdr.Read();
str.AppendLine(cmd.ExecuteScalar().ToString());
this.lblJDEtime.Text = str.ToString();
rdr.Close();
con.Close();
}
catch (OracleException err)
{
MessageBox.Show("Exception caught:\n\n" + err.ToString());
}
</code></pre>
<p>I've just updated the code needed to perform the connection. Changed the Exception type to the more specific OracleException. Added the connection string via Properties.Settings.</p>
|
[
{
"answer_id": 231073,
"author": "Loscas",
"author_id": 22706,
"author_profile": "https://Stackoverflow.com/users/22706",
"pm_score": 2,
"selected": true,
"text": "<p>Based on my experience with Oracle 10g....</p>\n\n<p>I recommend using the Oracle data provider (ODP.Net) and not using the Microsoft for Oracle data provider based on my experience with Oracle 10g. Microsoft's has not been updated in years and does not support everything in Oracle 10g, so I would definitely check into that for Oracle 8.</p>\n\n<p>Following <a href=\"http://msdn.microsoft.com/en-us/library/ms254494.aspx\" rel=\"nofollow noreferrer\">Microsoft guidance</a> on connection string in the app.config file, you should store it like:</p>\n\n<pre><code><?xml version='1.0' encoding='utf-8'?>\n <configuration>\n <connectionStrings>\n <clear />\n <add name=\"Name\" \n providerName=\"System.Data.ProviderName\" \n connectionString=\"Valid Connection String;\" />\n </connectionStrings>\n </configuration>\n</code></pre>\n\n<p>I've also worked on apps with the connection information stored in application settings, which worked fine for our application.</p>\n"
},
{
"answer_id": 231111,
"author": "BQ.",
"author_id": 4632,
"author_profile": "https://Stackoverflow.com/users/4632",
"pm_score": 0,
"selected": false,
"text": "<p>I would warn against building an architecture like you're suggesting. Opening a new connection to the database to poll for changes every second is an expensive operation. It gets worse if you're trying to scale this Windows Form application beyond a few users.</p>\n\n<p>Instead, you should look into the built-in Oracle packages that can support monitoring such activity.</p>\n\n<p>EDIT: \"WHERE ROWNUM=1\" from your example isn't useful here. Oracle isn't guaranteed to order the results in any specific way according to your query. </p>\n\n<p>Your issue is really an architectural problem. Polling database tables as you suggest is NOT a good way to do application health monitoring. At a bare minimum, you're better off having a component in the middle tier, or even the database, periodically write to a log file, Windows Event Log, table, etc. that essentially says \"I'm still listening\" and only poll THAT singular source.</p>\n"
},
{
"answer_id": 231493,
"author": "BQ.",
"author_id": 4632,
"author_profile": "https://Stackoverflow.com/users/4632",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a sample from our environment:</p>\n\n<pre><code><add key=\"ODP.NET.ConnectionString\" value=\"Password=abcdefg;Persist Security Info=True;User ID=abc123;Data Source=blah;\"/>\n</code></pre>\n\n<p>Where the username and password are set appropriately, and the Data Source is the entry from Oracle's TNSNAMES.ORA we're connecting to.</p>\n"
},
{
"answer_id": 231544,
"author": "Richard Nienaber",
"author_id": 9539,
"author_profile": "https://Stackoverflow.com/users/9539",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.connectionstrings.com/\" rel=\"nofollow noreferrer\">ConnectionStrings.com</a> has pretty much every type of connection string you'll ever want including <a href=\"http://www.connectionstrings.com/?carrier=oracle\" rel=\"nofollow noreferrer\">Oracle</a>.</p>\n"
},
{
"answer_id": 233298,
"author": "pero",
"author_id": 21645,
"author_profile": "https://Stackoverflow.com/users/21645",
"pm_score": 1,
"selected": false,
"text": "<p>@Loscas\nAFAIK ODP.NET data provider is supported only on Oracle 9i up. \n<a href=\"http://msdn.microsoft.com/en-us/library/a6cd7c08.aspx\" rel=\"nofollow noreferrer\">MS Oracle data provider</a> works on 8.1.7 and up.</p>\n\n<p>@BQ</p>\n\n<blockquote>\n <p>Opening a new connection to the database to poll for changes every second is an expensive operation.</p>\n</blockquote>\n\n<p>Actually the connection is not opened on con.Open(). It is just taken from the pool of open connections. con.Close() returns the connection to the pool. So, there is really nothing wrong with this connection handling.</p>\n"
},
{
"answer_id": 274574,
"author": "Kevin P.",
"author_id": 18542,
"author_profile": "https://Stackoverflow.com/users/18542",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to monitor tables, have you consider using triggers? An example might be:</p>\n\n<ul>\n<li>Your application listens on a TCP\nport</li>\n<li>You install a trigger on an\nOracle table</li>\n<li>The trigger calls some Oracle Java\ncode that ...</li>\n<li>... sends\na simple message to your app's TCP\nport</li>\n<li>The message could just be a\nnotification and you could then read\nfrom the table. Alternatively, you\ncould send the entire SQL that\naffected the table as the message\npayload.</li>\n</ul>\n\n<p>This might work better.</p>\n"
},
{
"answer_id": 274583,
"author": "Kevin P.",
"author_id": 18542,
"author_profile": "https://Stackoverflow.com/users/18542",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding the connection string, since you are using System.Data.OracleClient, I would also recommend formatting the Oracle connection string to make it independent of tnsname.ora:</p>\n\n<pre><code>string connectionString = @\"\nSERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP\n(HOST=OracleHost)(PORT=OraclePort))\n(CONNECT_DATA=(SERVICE_NAME=OracleServiceName)))\n;uid=UserID;pwd=Password;\";\n</code></pre>\n\n<p>You can store it in your App.config file like so:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <appSettings>\n <add key=\"My.Database.Connection\" value=\"SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP\n (HOST=OracleHost)(PORT=OraclePort))\n (CONNECT_DATA=(SERVICE_NAME=OracleServiceName)))\n ;uid=UserID;pwd=Password;\" />\n </appSettings>\n</configuration>\n</code></pre>\n\n<p>and then access it with:</p>\n\n<pre><code>connectionString = ConfigurationSettings.AppSettings[\"My.Database.Connection\"];\n</code></pre>\n\n<p>FYI, here is a blog post by me on this subject:\n<a href=\"http://mishandledexception.blogspot.com/2008/11/quick-and-dirty-connection-to-oracle.html\" rel=\"nofollow noreferrer\">Quick and dirty connection to Oracle using ADO.NET</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
I'm looking for best practices for establishing connections between Oracle 8 and Visual Studio 2005 applications. The target would be a Windows Forms application written in C# that hits the database once a second to monitor tables looking for their last inserted record. I'm considering using "Application settings" to store the connection string there, but I'd love to hear from you guys. Thanks in advance!
This is a very rudimentary draft:
```
using System.Data;
using System.Data.OracleClient;
try
{
StringBuilder str = new StringBuilder();
string ora = Properties.Settings.Default.OracleConnectionString;
OracleConnection con = new OracleConnection(ora);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT timestamp FROM jde_out WHERE rownum = 1";
cmd.CommandType = CommandType.Text;
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
rdr.Read();
str.AppendLine(cmd.ExecuteScalar().ToString());
this.lblJDEtime.Text = str.ToString();
rdr.Close();
con.Close();
}
catch (OracleException err)
{
MessageBox.Show("Exception caught:\n\n" + err.ToString());
}
```
I've just updated the code needed to perform the connection. Changed the Exception type to the more specific OracleException. Added the connection string via Properties.Settings.
|
Based on my experience with Oracle 10g....
I recommend using the Oracle data provider (ODP.Net) and not using the Microsoft for Oracle data provider based on my experience with Oracle 10g. Microsoft's has not been updated in years and does not support everything in Oracle 10g, so I would definitely check into that for Oracle 8.
Following [Microsoft guidance](http://msdn.microsoft.com/en-us/library/ms254494.aspx) on connection string in the app.config file, you should store it like:
```
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings>
<clear />
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
</configuration>
```
I've also worked on apps with the connection information stored in application settings, which worked fine for our application.
|
230,973 |
<p>I saw a code snippet yesterday in one of the responses here on StackOverflow that intrigued me. It was something like this:</p>
<pre><code> List<string> myList = new List<string> {"aBc", "HELLO", "GoodBye"};
myList.ForEach(d=>d.ToLower());
</code></pre>
<p>I was hoping I could use it to convert all items in myList to lowercase. However, it doesn't happen... after running this, the casing in myList is unchanged.</p>
<p>So my question is whether there IS a way, using LINQ and Lambda expressions to easily iterate through and modify the contents of a list in a manner similar to this.</p>
<p>Thanks,
Max</p>
|
[
{
"answer_id": 230991,
"author": "marcumka",
"author_id": 30761,
"author_profile": "https://Stackoverflow.com/users/30761",
"pm_score": 2,
"selected": false,
"text": "<pre><code>[TestMethod]\npublic void LinqStringTest()\n{\n List<string> myList = new List<string> { \"aBc\", \"HELLO\", \"GoodBye\" };\n myList = (from s in myList select s.ToLower()).ToList();\n Assert.AreEqual(myList[0], \"abc\");\n Assert.AreEqual(myList[1], \"hello\");\n Assert.AreEqual(myList[2], \"goodbye\");\n}\n</code></pre>\n"
},
{
"answer_id": 230995,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 6,
"selected": false,
"text": "<p>That's because ToLower <strong>returns</strong> a lowercase string rather than converting the original string. So you'd want something like this:</p>\n\n<pre><code>List<string> lowerCase = myList.Select(x => x.ToLower()).ToList();\n</code></pre>\n"
},
{
"answer_id": 231016,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 2,
"selected": false,
"text": "<p><code>ForEach</code> uses <code>Action<T></code>, which means that you could affect <code>x</code> if it were not immutable. Since <code>x</code> is a <code>string</code>, it is immutable, so nothing you do to it in the lambda will change its properties. Kyralessa's solution is your best option unless you want to implement your own extension method that allows you to return a replacement value.</p>\n"
},
{
"answer_id": 231019,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 9,
"selected": true,
"text": "<p>Easiest approach:</p>\n\n<pre><code>myList = myList.ConvertAll(d => d.ToLower());\n</code></pre>\n\n<p>Not too much different than your example code. <code>ForEach</code> loops the original list whereas <code>ConvertAll</code> creates a new one which you need to reassign.</p>\n"
},
{
"answer_id": 15266151,
"author": "Uhlamurile",
"author_id": 2082721,
"author_profile": "https://Stackoverflow.com/users/2082721",
"pm_score": -1,
"selected": false,
"text": "<pre><code>var _reps = new List(); // with variant data\n\n_reps.ConvertAll<string>(new Converter<string,string>(delegate(string str){str = str.ToLower(); return str;})).Contains(\"invisible\"))\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29662/"
] |
I saw a code snippet yesterday in one of the responses here on StackOverflow that intrigued me. It was something like this:
```
List<string> myList = new List<string> {"aBc", "HELLO", "GoodBye"};
myList.ForEach(d=>d.ToLower());
```
I was hoping I could use it to convert all items in myList to lowercase. However, it doesn't happen... after running this, the casing in myList is unchanged.
So my question is whether there IS a way, using LINQ and Lambda expressions to easily iterate through and modify the contents of a list in a manner similar to this.
Thanks,
Max
|
Easiest approach:
```
myList = myList.ConvertAll(d => d.ToLower());
```
Not too much different than your example code. `ForEach` loops the original list whereas `ConvertAll` creates a new one which you need to reassign.
|
230,981 |
<p>I am working with some input that is in the possible forms</p>
<pre><code>$1,200
20 cents/ inch
$10
</code></pre>
<p>Is there a way to parse these to numbers in VB? Also printing these numbers?</p>
<p><strong>EDIT:</strong> Regular expressions would be great.</p>
<p><strong>EDIT:</strong> VB 6 in particular</p>
|
[
{
"answer_id": 231025,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 2,
"selected": true,
"text": "<p>Ehh...Assuming all that you want is the digits, I would use a Regular Expression to simply replace any non-digit with \"\".</p>\n\n<p>You would need to reference Microsoft VBScript Regular Expressions in your project. Then let's say that your text was in a variable called strTest. Here is some off the cuff untested code:</p>\n\n<pre><code>Dim oRE As Object\nSet oRE = New VBScript_RegExp.RegExp\noRe.Pattern = \"\\D\"\nstrTest = oRE.Replace(strTest, \"\")\n</code></pre>\n"
},
{
"answer_id": 231092,
"author": "Will Rickards",
"author_id": 290835,
"author_profile": "https://Stackoverflow.com/users/290835",
"pm_score": 2,
"selected": false,
"text": "<p>You mean VB6/VBA or VB.net?\nIn VB6 or VBA you can do <code>CLng()</code>\nOr <code>CDec()</code> depending on what type of number you want.\nThey will deal with the beginning dollar sign and commas just fine.\nFor dealing with the 20 cents / inch you should probably do something like</p>\n\n<pre><code>CLng(split(\"20 cents / inch\", \" \")(0))\n</code></pre>\n\n<p>These functions throw a type conversion error if they can't convert.\nYou can trap that and try converting it another way if they fail.</p>\n\n<p>There is also a function called Val which returns the numeric portion.\nIt doesn't generate type conversion errors like <code>CDec</code>. But it also doesn't handle any non-numeric input. It gives you the decimal value of the digits in a string as long as it starts with a digit. It ignores any trailing characters.</p>\n"
},
{
"answer_id": 231717,
"author": "SystemSmith",
"author_id": 30987,
"author_profile": "https://Stackoverflow.com/users/30987",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes it just takes brute force!</p>\n\n<p>Here is a routine that takes in a string with numbers and returns a number properly handled with fractions, M or B suffixes, and more. You can modify i to handle any special condition or text algebra (miles / hour, cents / inch, etc)</p>\n\n<p>This is taken from one of our production applications thus the line numbers which we use in our error handler (ERHandler), as well as the standard exit routine.</p>\n\n<pre><code>Function GetNumberFromString(s As String) As Currency\n12800 Const ProcID = \"GetNumberFromString\"\n12810 Dim c As String\n12820 Dim d As Integer\n12830 Dim Denominator As Double ' currency only handles 4 places\n12840 Dim HaveDec As Boolean\n12850 Dim HaveSlash As Boolean\n12860 Dim HaveSpace As Boolean\n12870 Dim i As Integer\n12880 Dim LenV As Integer\n12890 Dim NegMult As Integer\n12900 Dim Numerator As Currency\n12910 Dim TempVal As Currency\n12920 Dim v As String\n\n 'Provides the functionality of VAL, but handles commas, fractions\n ' also million and billion\n\n12930 On Error GoTo ErrLbl\n12940 oLog.LogProcEntry ModuleID, ProcID, \"v=\" & v\n\n12950 v = Trim(s)\n12960 LenV = Len(v)\n12970 If LenV = 0 Then\n12980 GetNumberFromString = 0\n12990 GoTo ExitProc\n13000 End If\n13010 TempVal = 0\n13020 d = 0\n13030 NegMult = 1\n '\n13040 For i = 1 To LenV\n13050 c = Mid(v, i, 1)\n13060 Select Case c\n Case \"0\" To \"9\"\n13070 If HaveSpace Then\n13080 If Not HaveSlash Then\n13090 Numerator = 10 * Numerator + Asc(c) - 48\n13100 Else\n13110 Denominator = 10 * Denominator + Asc(c) - 48\n13120 End If\n13130 ElseIf Not HaveDec Then\n13140 TempVal = 10 * TempVal + Asc(c) - 48\n13150 Else\n13160 TempVal = TempVal + ((Asc(c) - 48)) / (10 ^ d)\n13170 d = d + 1\n13180 End If\n13190 Case \",\", \"$\"\n ' do nothing\n13200 Case \"-\" 'let handle negatives ns 12/20/96\n13210 NegMult = -1 * NegMult\n13220 Case \"(\" 'let handle negatives mt 6/9/99\n13230 NegMult = -1 * NegMult\n13240 Case \".\"\n13250 HaveDec = True\n13260 d = 1\n13270 Case \" \"\n13280 HaveSpace = True\n13290 d = 1\n13300 Case \"/\"\n13310 HaveSlash = True\n13320 If Not HaveSpace Then\n13330 HaveSpace = True\n13340 Numerator = TempVal\n13350 TempVal = 0\n13360 End If\n13370 Case \"b\", \"B\"\n13380 If UCase(Mid(v, i, 7)) = \"BILLION\" Then\n13390 TempVal = TempVal * 1000000000#\n13400 Exit For\n13410 End If\n13420 Case \"m\", \"M\"\n13430 If UCase(Mid(v, i, 7)) = \"MILLION\" Then\n13440 TempVal = TempVal * 1000000#\n13450 Exit For\n13460 End If\n13470 Case Else\n ' ignore character/error\n13480 End Select\n13490 Next i\n\n13500 If HaveSlash And Denominator <> 0 Then\n13510 TempVal = TempVal + Numerator / Denominator\n13520 End If\n\n13530 GetNumberFromString = TempVal * NegMult\n\nExitProc:\n13540 oLog.LogProcExit ModuleID, ProcID\n13550 Exit Function\n\nErrLbl:\n13560 Debug.Print Err.Description, Err.Number\n13570 Debug.Assert False\n13580 ERHandler ModuleID, ProcID\n13590 Resume\nEnd Function\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17712/"
] |
I am working with some input that is in the possible forms
```
$1,200
20 cents/ inch
$10
```
Is there a way to parse these to numbers in VB? Also printing these numbers?
**EDIT:** Regular expressions would be great.
**EDIT:** VB 6 in particular
|
Ehh...Assuming all that you want is the digits, I would use a Regular Expression to simply replace any non-digit with "".
You would need to reference Microsoft VBScript Regular Expressions in your project. Then let's say that your text was in a variable called strTest. Here is some off the cuff untested code:
```
Dim oRE As Object
Set oRE = New VBScript_RegExp.RegExp
oRe.Pattern = "\D"
strTest = oRE.Replace(strTest, "")
```
|
230,985 |
<p>I have a Delphi Web Server setup and running, publishing Web Services, and I want to know some stuff on the calls to the web services:</p>
<ul>
<li>The IP address of the client who calls the web service.</li>
<li>Some SOAP information on the call, such as username and password.</li>
</ul>
<p>How can I get this information from within the service code? My class is inheriting from TSoapDataModule, so I figure there's a way to get that info through it. Still, I can't find how.</p>
<pre><code>TMyAppServerDataModule = class(TSoapDataModule, ITMyAppServerDataModule ,
IAppServerSOAP, IAppServer, ITMySOAPWebService)
// ...my working components and methods... //
end;
</code></pre>
|
[
{
"answer_id": 254898,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 3,
"selected": true,
"text": "<p>You should be able to get a <a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/HTTPApp_TWebRequest.html\" rel=\"nofollow noreferrer\">TWebRequest</a> from the Request property of the TWebModule object you get from calling <a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/WebBrokerSOAP_GetSOAPWebModule.html\" rel=\"nofollow noreferrer\">GetSOAPWebModule</a>. TWebRequest will tell you lots of things about the request. Like RemoteAddr</p>\n"
},
{
"answer_id": 756119,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>See GetSOAPWebModule.Request (uses WebBrokerSoap;).</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16732/"
] |
I have a Delphi Web Server setup and running, publishing Web Services, and I want to know some stuff on the calls to the web services:
* The IP address of the client who calls the web service.
* Some SOAP information on the call, such as username and password.
How can I get this information from within the service code? My class is inheriting from TSoapDataModule, so I figure there's a way to get that info through it. Still, I can't find how.
```
TMyAppServerDataModule = class(TSoapDataModule, ITMyAppServerDataModule ,
IAppServerSOAP, IAppServer, ITMySOAPWebService)
// ...my working components and methods... //
end;
```
|
You should be able to get a [TWebRequest](http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/HTTPApp_TWebRequest.html) from the Request property of the TWebModule object you get from calling [GetSOAPWebModule](http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate3/EN/html/delphivclwin32/WebBrokerSOAP_GetSOAPWebModule.html). TWebRequest will tell you lots of things about the request. Like RemoteAddr
|
230,992 |
<p>I'm trying to create a table under SQL Server 2008 containing a <strong>GEOMETRY</strong> column and a calculated variation thereof.</p>
<p>Considering the following table where the calculated column returns a buffered geometry:</p>
<pre><code>CREATE TABLE [dbo].[Test] (
[Geometry] GEOMETRY NOT NULL,
[Buffer] FLOAT NOT NULL,
[BufferedGeometry] AS ([Geometry].STBuffer([Buffer])) PERSISTED
);
</code></pre>
<p>The problem with this is it results in the following error:</p>
<blockquote>
<p>Msg 4994, Level 16, State 1, Line 2
Computed column 'BufferedGeometry' in
table 'Test' cannot be persisted
because the column type, 'geometry',
is a non-byte-ordered CLR type.</p>
</blockquote>
<p>I have search BOL and the web and can't seem to find a solution to my problem. I really would like it to be persisted so I can index it effectively. I could set it in code, but then I have the possibility of inconsistent data as I require both values at some point in time.</p>
<p>Anyone played with this and know a solution or workaround?</p>
<p><strong>Update: Microsoft has added this functionality in SQL Server 2012.</strong></p>
|
[
{
"answer_id": 231758,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 2,
"selected": false,
"text": "<p>I guess you could use a trigger to calculate it and store it to the [BufferedGeometry] field</p>\n"
},
{
"answer_id": 17833715,
"author": "root",
"author_id": 246557,
"author_profile": "https://Stackoverflow.com/users/246557",
"pm_score": 1,
"selected": false,
"text": "<p>Whoever is still having such problem: SQL Server 2012 now allows it</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/230992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28305/"
] |
I'm trying to create a table under SQL Server 2008 containing a **GEOMETRY** column and a calculated variation thereof.
Considering the following table where the calculated column returns a buffered geometry:
```
CREATE TABLE [dbo].[Test] (
[Geometry] GEOMETRY NOT NULL,
[Buffer] FLOAT NOT NULL,
[BufferedGeometry] AS ([Geometry].STBuffer([Buffer])) PERSISTED
);
```
The problem with this is it results in the following error:
>
> Msg 4994, Level 16, State 1, Line 2
> Computed column 'BufferedGeometry' in
> table 'Test' cannot be persisted
> because the column type, 'geometry',
> is a non-byte-ordered CLR type.
>
>
>
I have search BOL and the web and can't seem to find a solution to my problem. I really would like it to be persisted so I can index it effectively. I could set it in code, but then I have the possibility of inconsistent data as I require both values at some point in time.
Anyone played with this and know a solution or workaround?
**Update: Microsoft has added this functionality in SQL Server 2012.**
|
I guess you could use a trigger to calculate it and store it to the [BufferedGeometry] field
|
231,023 |
<p>I'd like to align label/value pairs in the center using CSS without using absolute positioning or tables (see screen shot). In that screen shot I positioned the value (ie. $4,500/wk) absolute and then floated the label right up against it. But absolute doesn't work so well in IE and I've heard it's not a good technique.</p>
<p>But how can I acheive this effect where the labels are all justified right without absolute?</p>
<p><a href="http://www.amherstparents.org/files/shot.jpg" rel="nofollow noreferrer">alt text http://www.amherstparents.org/files/shot.jpg</a></p>
|
[
{
"answer_id": 231030,
"author": "Jon Tackabury",
"author_id": 343,
"author_profile": "https://Stackoverflow.com/users/343",
"pm_score": 4,
"selected": false,
"text": "<p>If you're showing tabular data there's no shame in using a table.</p>\n"
},
{
"answer_id": 231033,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 2,
"selected": false,
"text": "<p>Use fixed width divs with the CSS <a href=\"http://www.w3schools.com/CSS/pr_text_text-align.asp\" rel=\"nofollow noreferrer\">text-align</a> property. Don't forget to float your divs left.</p>\n"
},
{
"answer_id": 231056,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 2,
"selected": false,
"text": "<p>Let's say you're using DL, DT and DD:</p>\n\n<pre><code><dl>\n<dt>Cost:</dt>\n<dd>$4,500/wk</dd>\n<dt>Sleeps:</dt>\n<dd>1</dd>\n</dl>\n</code></pre>\n\n<p>You can use the following approximate CSS (untested):</p>\n\n<pre><code>dl { width: 200px; }\ndt { width: 100px; text-align: right; float: left; clear: both; }\ndd { width: 100px; margin: 0; float: left; }\n</code></pre>\n\n<p>Edit: As Chris Marasti-Georg pointed out:</p>\n\n<blockquote>\n <p>Additionally, if you want 2 columns,\n use 2 definition lists, and float them</p>\n</blockquote>\n"
},
{
"answer_id": 231078,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 2,
"selected": false,
"text": "<p>@jon is right, if its tabular data, you can use a table. However, if you really don't want to use a table, I think this is what you want:</p>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>.label {\n min-width: 20%;\n text-align: right;\n float: left;\n}\n</code></pre>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><div class=\"pair\">\n <div class=\"label\">Cost</div>\n <div class=\"value\">$4,500/wk</div>\n</div>\n<div class=\"pair\">\n <div class=\"label\">Sleeps</div>\n <div class=\"value\">1</div>\n</div>\n<div class=\"pair\">\n <div class=\"label\">Bedrooms</div>\n <div class=\"value\">9</div>\n</div>\n</code></pre>\n\n<p><strong>EDIT</strong> @Chris Marasti-Georg points out that definition lists would be more appropriate here. I agree, but I guess I wanted to show that the same can be easily done with any block-level element, and there is nothing in the default styling of definition lists that is needed to accomplish this goal.</p>\n"
},
{
"answer_id": 231120,
"author": "BoboTheCodeMonkey",
"author_id": 30532,
"author_profile": "https://Stackoverflow.com/users/30532",
"pm_score": 0,
"selected": false,
"text": "<p>How about using a table to layout the table and then using CSS to position that table wherever you want on your page?</p>\n"
},
{
"answer_id": 231164,
"author": "Mike",
"author_id": 25371,
"author_profile": "https://Stackoverflow.com/users/25371",
"pm_score": 2,
"selected": false,
"text": "<p>Expanding on Rahul's post:</p>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#list { width: 450px; }\n#left { float: left; background: lightgreen; }\n#right { float: right; background: lightblue; }\ndl { width: 225px; }\ndt { width: 100px; text-align: right; float: left; clear: both; }\ndd { width: 100px; margin: 0; float: left; padding-left: 5px; }\n</code></pre>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><div id=\"list\">\n <dl id=\"left\">\n <dt>Cost:</dt>\n <dd>$4,500/wk</dd>\n <dt>Sleeps:</dt>\n <dd>1</dd>\n <dt>Bedrooms:</dt>\n <dd>9</dd>\n <dt>Baths:</dt>\n <dd>6</dd>\n </dl>\n <dl id=\"right\">\n <dt>Pets:</dt>\n <dd>No</dd>\n <dt>Smoking:</dt>\n <dd>No</dd>\n <dt>Pool:</dt>\n <dd>No</dd>\n <dt>Waterfront:</dt>\n <dd>No</dd>\n </dl>\n</div>\n</code></pre>\n\n<p>I tested this under FF 3.0.1, IE6 and IE7. The background color is simply there to help you visualize where the columns start and end.</p>\n"
},
{
"answer_id": 231176,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 0,
"selected": false,
"text": "<p>A quick note on implementing this using tables, there are several constructs that will make this plenty accessible. The simplest of which would simple to be to use TH for the labels and TD for the values. <a href=\"http://www.usability.com.au/resources/tables.cfm\" rel=\"nofollow noreferrer\">This site</a> has a nice discussion, and goes deeper into things like headers for cells, etc.</p>\n"
},
{
"answer_id": 231311,
"author": "Lee Kowalkowski",
"author_id": 30945,
"author_profile": "https://Stackoverflow.com/users/30945",
"pm_score": 4,
"selected": true,
"text": "<p>I'm confused, what's tabular about that data? Where are the records? Rows of different fields do not really make a table in the traditional sense. (Nor hacking it to have two records per row for that matter) </p>\n\n<p>If we're entertaining this idea, then what's the difference between the left half of the table and the right? What would the column headings be if there were any?</p>\n\n<p>I prefer the definition list suggestion, it's definitely a better fit than a table. And you wouldn't need two columns if all the DTs and DDs were float:left and width:25%, and in the following order: Cost, Pets, Sleeps, Smoking, etc... Therefore you can use 1 definition list, as it really ought to be.</p>\n\n<p>Although you will probably need a clear:left on every other DT just in case the content of any of these elements wraps over two lines.</p>\n\n<pre><code><style>\n dl\n {\n float:left;\n width:100%;\n }\n dt,\n dd\n {\n float:left;\n width:24%;\n margin:0;\n padding:0;\n }\n dt\n {\n text-align:right;\n padding-right:.33em;\n }\n dd\n {\n text-align:left;\n }\n</style>\n<dl>\n <dt>Cost:</dt>\n <dd>$4,500/wk</dd>\n <dt>Pets:</dt>\n <dd>No</dd>\n <dt>Sleeps:</dt>\n <dd>1</dd>\n <dt>Smoking:</dt>\n <dd>No</dd>\n</dl>\n</code></pre>\n"
},
{
"answer_id": 232782,
"author": "mdja",
"author_id": 31098,
"author_profile": "https://Stackoverflow.com/users/31098",
"pm_score": 0,
"selected": false,
"text": "<p>I've always treated definition lists as to be used for <em>definitions</em> of items, not for key/value pairs. (9 is not a definition of 'bedrooms'). However, this particular construct (lists of key/value pairs) has been causing arguments for years as there is no native semantic markup which reflects it properly. </p>\n\n<p>Go for a DL if you're not anal about what a definition is. Or go for a table. A table with key/value pairs in rows, if the header/cell scope is set correctly, is perfectly valid. I've been doing this recently, and it does seem to be the most semantically accurate representation. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6957/"
] |
I'd like to align label/value pairs in the center using CSS without using absolute positioning or tables (see screen shot). In that screen shot I positioned the value (ie. $4,500/wk) absolute and then floated the label right up against it. But absolute doesn't work so well in IE and I've heard it's not a good technique.
But how can I acheive this effect where the labels are all justified right without absolute?
[alt text http://www.amherstparents.org/files/shot.jpg](http://www.amherstparents.org/files/shot.jpg)
|
I'm confused, what's tabular about that data? Where are the records? Rows of different fields do not really make a table in the traditional sense. (Nor hacking it to have two records per row for that matter)
If we're entertaining this idea, then what's the difference between the left half of the table and the right? What would the column headings be if there were any?
I prefer the definition list suggestion, it's definitely a better fit than a table. And you wouldn't need two columns if all the DTs and DDs were float:left and width:25%, and in the following order: Cost, Pets, Sleeps, Smoking, etc... Therefore you can use 1 definition list, as it really ought to be.
Although you will probably need a clear:left on every other DT just in case the content of any of these elements wraps over two lines.
```
<style>
dl
{
float:left;
width:100%;
}
dt,
dd
{
float:left;
width:24%;
margin:0;
padding:0;
}
dt
{
text-align:right;
padding-right:.33em;
}
dd
{
text-align:left;
}
</style>
<dl>
<dt>Cost:</dt>
<dd>$4,500/wk</dd>
<dt>Pets:</dt>
<dd>No</dd>
<dt>Sleeps:</dt>
<dd>1</dd>
<dt>Smoking:</dt>
<dd>No</dd>
</dl>
```
|
231,027 |
<p>I make a request to an xml web service, and get back a response. This response, being a stream, is then saved to a string. The problem is, the response is full of tags, CDATA, etc (as you would expect). There is no line breaking either, as to be expected.</p>
<p>I want to take this string, which represents an xml document, and strip it of all its tags but keep the actual values, and also, make sure that each record is in one line, so:</p>
<pre><code><Record>
<name>adam</name>
<telephoneno>000</telephonenumber>
</Record>
<Record>
<name>mike</name>
<telephoneno>001</telephonenumber>
</Record>
</code></pre>
<p>Will be transformed to:</p>
<pre><code>adam 000
mike 001
</code></pre>
<p>Headings is an easy issue, but how could I achieve this? I've tried datatables and datasets but I don't think they have great support for achieving what I am trying to do.</p>
|
[
{
"answer_id": 231041,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 3,
"selected": false,
"text": "<p>This is exactly what XSLT is for! It transforms XML files into a different output. In your case, you could use a relatively simple XSL transformation to output a list.</p>\n\n<p>This might do it:</p>\n\n<p>records.xml:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"style.xsl\"?>\n<Records>\n <Record>\n <name>adam</name>\n <telephonenumber>000</telephonenumber>\n </Record>\n <Record>\n <name>mike</name>\n <telephonenumber>001</telephonenumber>\n </Record>\n</Records>\n</code></pre>\n\n<p>style.xsl</p>\n\n<pre><code><xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output method=\"text\" omit-xml-declaration=\"yes\" indent=\"no\"/>\n <xsl:template match=\"Record\">\n <xsl:value-of select=\"name\"/><xsl:text> </xsl:text><xsl:value-of select=\"telephonenumber\"/>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n\n<p>I tested it with <a href=\"http://www.netcrucible.com/xslt/xslt-tool.htm\" rel=\"nofollow noreferrer\">this tool</a> and it works.</p>\n"
},
{
"answer_id": 231063,
"author": "BQ.",
"author_id": 4632,
"author_profile": "https://Stackoverflow.com/users/4632",
"pm_score": 0,
"selected": false,
"text": "<p>Michael Haren's XSLT response is the best answer.</p>\n\n<p>But alternatively if you're not actually wanting the response as XML you can return whatever it is that you DO desire from the web service (provided it's yours, rather than a third party service). </p>\n\n<p>There's no rule that says a web service must return XML. Just make sure to serve the appropriate MIME-Type.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I make a request to an xml web service, and get back a response. This response, being a stream, is then saved to a string. The problem is, the response is full of tags, CDATA, etc (as you would expect). There is no line breaking either, as to be expected.
I want to take this string, which represents an xml document, and strip it of all its tags but keep the actual values, and also, make sure that each record is in one line, so:
```
<Record>
<name>adam</name>
<telephoneno>000</telephonenumber>
</Record>
<Record>
<name>mike</name>
<telephoneno>001</telephonenumber>
</Record>
```
Will be transformed to:
```
adam 000
mike 001
```
Headings is an easy issue, but how could I achieve this? I've tried datatables and datasets but I don't think they have great support for achieving what I am trying to do.
|
This is exactly what XSLT is for! It transforms XML files into a different output. In your case, you could use a relatively simple XSL transformation to output a list.
This might do it:
records.xml:
```
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<Records>
<Record>
<name>adam</name>
<telephonenumber>000</telephonenumber>
</Record>
<Record>
<name>mike</name>
<telephonenumber>001</telephonenumber>
</Record>
</Records>
```
style.xsl
```
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="Record">
<xsl:value-of select="name"/><xsl:text> </xsl:text><xsl:value-of select="telephonenumber"/>
</xsl:template>
</xsl:stylesheet>
```
I tested it with [this tool](http://www.netcrucible.com/xslt/xslt-tool.htm) and it works.
|
231,029 |
<p>I am trying to include a value from a database table within the value element of an input field.<br>
This is what I have, but it is not working:</p>
<pre><code>?><input type="text" size="10" value="<?= date("Y-m-d",
strtotime($rowupd['upcoming_event_featured_date'])) ?>" name="upcoming_event_featured_date"
id="keys"/><?php
</code></pre>
<p>I have done this before, but I usually print it out like this:</p>
<pre><code>print '<input type="text" size="10" value="'.date("Y-m-d",
strtotime($rowupd['upcoming_event_featured_date'])).'" name="upcoming_event_featured_date"
id="keys"/>';
</code></pre>
<p>What is the appropriate way of doing this without using <code>print ''</code>?</p>
|
[
{
"answer_id": 231037,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <a href=\"http://us.php.net/manual/en/ini.core.php#ini.short-open-tag\" rel=\"nofollow noreferrer\">short_open_tag</a> ini directive to turn on the <?= shortcut for printing.</p>\n\n<p>If that is not available, you must use either print or echo to accomplish this.</p>\n\n<p>You can try:</p>\n\n<pre><code>ini_set('short_open_tag', true);\n</code></pre>\n"
},
{
"answer_id": 231058,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 0,
"selected": false,
"text": "<p>You can do</p>\n\n<pre><code>[...] ?><input \n type=\"text\" \n size=\"10\" \n value=\"<?php echo date(\"Y-m-d\", strtotime($rowupd['upcoming_event_featured_date'])) ?>\" \n name=\"upcoming_event_featured_date\" \n id=\"keys\"/>\n<?php [...]\n</code></pre>\n\n<p>if you don't have <code>short_open_tag</code> enabled in your PHP configuration.</p>\n"
},
{
"answer_id": 231085,
"author": "Eli",
"author_id": 27580,
"author_profile": "https://Stackoverflow.com/users/27580",
"pm_score": 3,
"selected": true,
"text": "<p>It's a good idea to always use full PHP tags, because that will keep your app from breaking if you move to a different server or your config is changed not to allow short tags.</p>\n\n<pre><code>?>\n<input type=\"text\" size=\"10\" value=\"<?php\necho(date(\"Y-m-d\", strtotime($rowupd['upcoming_event_featured_date'])));\n?>\"name=\"upcoming_event_featured_date\" id=\"keys\"/><?php\n</code></pre>\n\n<p>Also, note that you are missing the <code>;</code> from the end of your PHP code.</p>\n\n<p>You may find it better to keep the whole thing in PHP too, and just <code>echo()</code> out the HTML, as that will keep you from having to switch back and forth from PHP to HTML parsing.</p>\n"
},
{
"answer_id": 234908,
"author": "Zac",
"author_id": 5630,
"author_profile": "https://Stackoverflow.com/users/5630",
"pm_score": 2,
"selected": false,
"text": "<p>As some other replies have mentioned, make sure <code>short_open_tag</code> is enabled in your php.ini. This lets you use the <code><?=</code> syntax. A lot of people recommend not using short tags, since not all servers allow them, but if you're sure you won't be moving this to another server, I think it's fine.</p>\n\n<p>Besides that, I don't know of any technical reason to choose one way over the other. Code readability should be your main focus. For example, you might want to set your value to a variable before outputting it:</p>\n\n<pre><code>$featured_date = date(\"Y-m-d\",strtotime($rowupd['featured_date']));\n\n?><input type=\"text\" value=\"<?=$featured_date?>\" name=\"featured_date\" /><?php\n</code></pre>\n\n<p>In fact, I'd try to do as little processing as possible while you're in the middle of a block of HTML. Things will be a lot cleaner if you define all your variables at the beginning of the script, then output all of the HTML, inserting the variables as needed. You're almost getting into templating at that point, but without needing the overhead of a template engine.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
I am trying to include a value from a database table within the value element of an input field.
This is what I have, but it is not working:
```
?><input type="text" size="10" value="<?= date("Y-m-d",
strtotime($rowupd['upcoming_event_featured_date'])) ?>" name="upcoming_event_featured_date"
id="keys"/><?php
```
I have done this before, but I usually print it out like this:
```
print '<input type="text" size="10" value="'.date("Y-m-d",
strtotime($rowupd['upcoming_event_featured_date'])).'" name="upcoming_event_featured_date"
id="keys"/>';
```
What is the appropriate way of doing this without using `print ''`?
|
It's a good idea to always use full PHP tags, because that will keep your app from breaking if you move to a different server or your config is changed not to allow short tags.
```
?>
<input type="text" size="10" value="<?php
echo(date("Y-m-d", strtotime($rowupd['upcoming_event_featured_date'])));
?>"name="upcoming_event_featured_date" id="keys"/><?php
```
Also, note that you are missing the `;` from the end of your PHP code.
You may find it better to keep the whole thing in PHP too, and just `echo()` out the HTML, as that will keep you from having to switch back and forth from PHP to HTML parsing.
|
231,051 |
<p>After reading <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip130.html?page=2" rel="noreferrer">this old article</a> measuring the memory consumption of several object types, I was amazed to see how much memory <code>String</code>s use in Java:</p>
<pre><code>length: 0, {class java.lang.String} size = 40 bytes
length: 7, {class java.lang.String} size = 56 bytes
</code></pre>
<p>While the article has some tips to minimize this, I did not find them entirely satisfying. It seems to be wasteful to use <code>char[]</code> for storing the data. The obvious improvement for most western languages would be to use <code>byte[]</code> and an encoding like UTF-8 instead, as you only need a single byte to store the most frequent characters then instead of two bytes.</p>
<p>Of course one could use <code>String.getBytes("UTF-8")</code> and <code>new String(bytes, "UTF-8")</code>. Even the overhead of the String instance itself would be gone. But then there you lose very handy methods like <code>equals()</code>, <code>hashCode()</code>, <code>length()</code>, ...</p>
<p>Sun has a <a href="http://www.freepatentsonline.com/6751790.html" rel="noreferrer">patent</a> on <code>byte[]</code> representation of Strings, as far as I can tell.</p>
<blockquote>
<p><strong>Frameworks for efficient representation of string objects in Java programming environments</strong><br />
... The techniques can be implemented to create Java string objects as arrays of one-byte characters when it is appropriate ...</p>
</blockquote>
<p>But I failed to find an API for that patent.</p>
<p>Why do I care?<br />
In most cases I don't. But I worked on applications with huge caches, containing lots of Strings, which would have benefitted from using the memory more efficiently.</p>
<p>Does anybody know of such an API? Or is there another way to keep your memory footprint for Strings small, even at the cost of CPU performance or uglier API?</p>
<p>Please don't repeat the suggestions from the above article:</p>
<ul>
<li>own variant of <code>String.intern()</code> (possibly with <code>SoftReferences</code>)</li>
<li>storing a single <code>char[]</code> and exploiting the current <code>String.subString(.)</code> implementation to avoid data copying (nasty)</li>
</ul>
<p><strong>Update</strong></p>
<p>I ran the code from the article on Sun's current JVM (1.6.0_10). It yielded the same results as in 2002.</p>
|
[
{
"answer_id": 231067,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Out of curiosity, is the few bytes saved really worth it?</p>\n\n<p>Normally, I suggest ditching strings for performance reasons, in favor of StringBuffer (Remember, Strings are immutable).</p>\n\n<p>Are you seriously exhausting your heap from string references?</p>\n"
},
{
"answer_id": 231074,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 2,
"selected": false,
"text": "<p>Just compress them all with gzip. :) Just kidding... but I have seen stranger things, and it would give you much smaller data at significant CPU expense.</p>\n\n<p>The only other String implementations that I'm aware of are the ones in the Javolution classes. I don't think that they are more memory efficient, though:</p>\n\n<p><a href=\"http://www.javolution.com/api/javolution/text/Text.html\" rel=\"nofollow noreferrer\">http://www.javolution.com/api/javolution/text/Text.html</a><br />\n<a href=\"http://www.javolution.com/api/javolution/text/TextBuilder.html\" rel=\"nofollow noreferrer\">http://www.javolution.com/api/javolution/text/TextBuilder.html</a></p>\n"
},
{
"answer_id": 231227,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 3,
"selected": false,
"text": "<p>I think you should be very cautious about basing any ideas and/or assumptions off of a javaworld.com article from 2002. There have been many, many changes to the compiler and JVM in the six years since then. At the very least, test your hypothesis and solution against a modern JVM first to make sure that the solution is even worth the effort.</p>\n"
},
{
"answer_id": 231291,
"author": "nkr1pt",
"author_id": 24046,
"author_profile": "https://Stackoverflow.com/users/24046",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that Strings are less memory intensive for some time now, because the Java engineers have implemented the flyweight design pattern to share as much as possible.\nIn fact Strings that have the same value point to the very same object in memory I believe.</p>\n"
},
{
"answer_id": 231352,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 0,
"selected": false,
"text": "<p>You said not to repeat the article's suggestion of rolling your own interning scheme, but what's wrong with <code>String.intern</code> itself? The article contains the following throwaway remark:</p>\n\n<blockquote>\n <p>Numerous reasons exist to avoid the String.intern() method. One is that few modern JVMs can intern large amounts of data.</p>\n</blockquote>\n\n<p>But even if the memory usage figures from 2002 still hold six years later, I'd be surprised if no progress has been made on how much data JVMs can intern.</p>\n\n<p>This isn't purely a rhetorical question - I'm interested to know if there are good reasons to avoid it. Is it implemented inefficiently for highly-multithreaded use? Does it fill up some special JVM-specific area of the heap? Do you really have hundreds of megabytes of unique strings (so interning would be useless anyway)?</p>\n"
},
{
"answer_id": 231404,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 1,
"selected": false,
"text": "<p>There is the overhead of creating an object (at least a dispatch table), the overhead of the fact that it uses 2 bytes per letter, and the overhead of a few extra variables in there that are created to actually improve speed and memory usage in many cases.</p>\n\n<p>If you are going to use OO programming, this is the cost of having clear, usable, maintainable code.</p>\n\n<p>For an answer besides the obvious (which is that if memory usage is that important, you should probably be using C), you could implement your own Strings with an internal representation in BCD byte-arrays.</p>\n\n<p>That actually sounds fun, I might do it just for kicks :)</p>\n\n<p>A Java array takes 2 bytes per item. A BCD encoded digit takes 6 bits per letter IIRC, making your strings significantly smaller. There would be a little conversion cost in time, but not too bad really. The really big problem is that you'd have to convert to string to do anything with it.</p>\n\n<p>You still have the overhead of an object instance to worry about... but that would be better addressed by revamping your design than trying to eliminate instances.</p>\n\n<p>Finally a note. I'm completely against deploying anything like this unless you have 3 things:</p>\n\n<ul>\n<li>An implementation done the most readable way</li>\n<li>Test results and requirements showing how that implementation doesn't meet requirements</li>\n<li>Test results on how the \"improved\" implementation DOES meet requirements.</li>\n</ul>\n\n<p>Without all three of those, I'd kick any optimized solution a developer presented to me.</p>\n"
},
{
"answer_id": 231474,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "<p>Java chose UTF-16 for a compromise of speed and storage size. Processing UTF-8 data is much more PITA than processing UTF-16 data (e.g. when trying to find the position of character X in the byte array, how are you going to do so in a fast manner, if every character can have one, two, three or even up to six bytes? Ever thought about that? Going over the string byte by byte is not really fast, you see?). Of course UTF-32 would be easiest to process, but waste twice the storage space. Things have changed since the early Unicode days. Now certain characters need 4 byte, even when UTF-16 is used. Handling these correctly make UTF-16 almost equally bad as UTF-8.</p>\n\n<p>Anyway, rest assured that if you implement a String class with an internal storage that uses UTF-8, you might win some memory, but you will lose processing speed for many string methods. Also your argument is a way too limited point of view. Your argument will not hold true for someone in Japan, since Japanese characters will not be smaller in UTF-8 than in UTF-16 (actually they will take 3 bytes in UTF-8, while they are only two bytes in UTF-16). I don't understand why programmers in such a global world like today with the omnipresent Internet still talk about \"western languages\", as if this is all that would count, as if only the western world has computers and the rest of it lives in caves. Sooner or later any application gets bitten by the fact that it fails to effectively process non-western characters.</p>\n"
},
{
"answer_id": 231490,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 3,
"selected": false,
"text": "<p>An internal UTF-8 encoding has its advantages (such as the smaller memory footprint that you pointed out), but it has disadvantages too.</p>\n\n<p>For example, determining the character-length (rather than the byte-length) of a UTF-8 encoded string is an O(n) operation. In a java string, the cost of determining the character-length is O(1), while generating the UTF-8 representation is O(n).</p>\n\n<p>It's all about priorities.</p>\n\n<p>Data-structure design can often be seen as a tradeoff between speed and space. In this case, I think the designers of the Java string API made a choice based on these criteria:</p>\n\n<ul>\n<li><p>The String class must support all possible unicode characters.</p></li>\n<li><p>Although unicode defines 1 byte, 2 byte, and 4-byte variants, the 4-byte characters are (in practice) pretty rare, so it's okay to represent them as surrogate pairs. That's why java uses a 2-byte char primitive.</p></li>\n<li><p>When people call length(), indexOf(), and charAt() methods, they're interested in the character position, not the byte position. In order to create fast implementations of these methods, it's necessary to avoid the internal UTF-8 encoding.</p></li>\n<li><p>Languages like C++ make the programmer's life more complicated by defining three different character types and forcing the programmer to choose between them. Most programmers start off using simple ASCII strings, but when they eventually need to support international characters, the process of modifying the code to use multibyte characters is extremely painful. I think the Java designers made an excellent compromise choice by saying that all strings consist of 2-byte characters.</p></li>\n</ul>\n"
},
{
"answer_id": 231608,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 3,
"selected": false,
"text": "<p>The article points out two things:</p>\n\n<ol>\n<li>Character arrays increase in chunks of 8 bytes.</li>\n<li>There is a large difference in size between char[] and String objects.</li>\n</ol>\n\n<p>The overhead is due to including a char[] object reference, and three ints: an offset, a length, and space for storing the String's hashcode, plus the standard overhead of simply being an object.</p>\n\n<p>Slightly different from String.intern(), or a character array used by String.substring() is using a single char[] for all Strings, this means you do not need to store the object reference in your wrapper String-like object. You would still need the offset, and you introduce a (large) limit on how many characters you can have in total.</p>\n\n<p>You would no longer need the length if you use a special end of string marker. That saves four bytes for the length, but costs you two bytes for the marker, plus the additional time, complexity, and buffer overrun risks.</p>\n\n<p>The space-time trade-off of not storing the hash may help you if you do not need it often.</p>\n\n<p>For an application that I've worked with, where I needed super fast and memory efficient treatment of a large number of strings, I was able to leave the data in its encoded form, and work with byte arrays. My output encoding was the same as my input encoding, and I didn't need to decode bytes to characters nor encode back to bytes again for output.</p>\n\n<p>In addition, I could leave the input data in the byte array it was originally read into - a memory mapped file.</p>\n\n<p>My objects consisted of an int offset (the limit suited my situation), an int length, and an int hashcode.</p>\n\n<p>java.lang.String was the familiar hammer for what I wanted to do, but not the best tool for the job.</p>\n"
},
{
"answer_id": 232557,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 4,
"selected": false,
"text": "<p>At Terracotta, we have some cases where we compress big Strings as they are sent around the network and actually leave them compressed until decompression is necessary. We do this by converting the char[] to byte[], compressing the byte[], then encoding that byte[] back into the original char[]. For certain operations like hash and length, we can answer those questions without decoding the compressed string. For data like big XML strings, you can get substantial compression this way.</p>\n\n<p>Moving the compressed data around the network is a definite win. Keeping it compressed is dependent on the use case. Of course, we have some knobs to turn this off and change the length at which compression turns on, etc. </p>\n\n<p>This is all done with byte code instrumentation on java.lang.String which we've found is very delicate due to how early String is used in startup but is stable if you follow some guidelines.</p>\n"
},
{
"answer_id": 237524,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 0,
"selected": false,
"text": "<p>Remember that there are many types of compression. Using huffman encoding is a good general purpose approach - but it is relatively CPU intensive. For a B+Tree implementation I worked on a few years back, we knew that the keys would likely have common leading characters, so we implemented a leading character compression algorithm for each page in the B+Tree. The code was easy, very, very fast, and resulted in a memory usage 1/3 of what we started with. In our case, the real reason for doing this was to save space on disk, and reduce time spent on disk -> RAM transfers (and that 1/3 savings made a huge difference in effective disk performance).</p>\n\n<p>The reason that I bring this up is that a custom String implementation wouldn't have helped very much here. We were only able to achieve the gains we did because we worked the layer of the <em>container</em> that the strings live in.</p>\n\n<p>Trying to optimize a few bytes here and there inside the String object may not be worth it in comparison.</p>\n"
},
{
"answer_id": 3323724,
"author": "J. Dimeo",
"author_id": 198371,
"author_profile": "https://Stackoverflow.com/users/198371",
"pm_score": 1,
"selected": false,
"text": "<p>I'm currently implementing a compression method as follows (I'm working on an app that needs to store a very large number of documents in memory so we can do document-to-document computation):</p>\n\n<ul>\n<li>Split up the string into 4-character \"words\" (if you need all Unicode) and store those bytes in a <code>long</code> using masking/bit shifting. If you don't need the full Unicode set and just the 255 ASCII characters, you can fit 8 characters into each <code>long</code>. Add <code>(char) 0</code> to the end of the string until the length divides evenly by 4 (or 8).</li>\n<li>Override a hash set implementation (like Trove's <code>TLongHashSet</code>) and add each \"word\" to that set, compiling an array of the internal indexes of where the <code>long</code> ends up in the set (make sure you also update your index when the set gets rehashed)</li>\n<li>Use a two-dimensional <code>int</code> array to store these indexes (so the first dimension is each compressed string, and the second dimension is each \"word\" index in the hash set), and return the single <code>int</code> index into that array back to the caller (you have to own the word arrays so you can globally update the index on a rehash as mentioned above)</li>\n</ul>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Constant time compression/decompression</li>\n<li>A length <em>n</em> string is represented as an <code>int</code> array of length <em>n</em>/4, with the additional overhead of the <code>long</code> word set which grows asymptotically as fewer unique \"words\" are encountered</li>\n<li>The user is handed back a single <code>int</code> string \"ID\" which is convenient and small to store in their objects</li>\n</ul>\n\n<p>Distadvantages:</p>\n\n<ul>\n<li>Somewhat hacky since it involves bit shifting, messing with the internals of the hash set, etc. (<a href=\"https://stackoverflow.com/users/12943/bill-k\">Bill K</a> would not approve)</li>\n<li>Works well when you don't expect a lot of duplicate strings. It's very expensive to check to see if a string already exists in the library.</li>\n</ul>\n"
},
{
"answer_id": 3324284,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 1,
"selected": false,
"text": "<p>Today (2010), each GB you add to a server costs about £80 or $120. Before you go re-engineering the String, you should ask yourself it is really worth it.</p>\n\n<p>If you are going to save a GB of memory, perhaps. Ten GB, definitiely. If you want to save 10s of MB, you are likely to use more time than its worth.</p>\n\n<p>How you compact the Strings really depends on your usage pattern. Are there lots of repeated strings? (use an object pool) Are there lots of long strings? (use compression/encoding)</p>\n\n<p>Another reason you might want smaller strings is to reduce cache usage. Even the largest CPUs have about 8 MB - 12 MB of cache. This can be a more precious resource and not easily increased. In this case I suggest you look at alternatives to strings, but you must have in mind how much difference it will make in £ or $ against the time it takes.</p>\n"
},
{
"answer_id": 4402560,
"author": "haylem",
"author_id": 453590,
"author_profile": "https://Stackoverflow.com/users/453590",
"pm_score": 5,
"selected": false,
"text": "<h1>With a Little Bit of Help From the JVM...</h1>\n\n<p><em><strong>WARNING:</strong> This solution is now obsolete in newer Java SE versions. See other ad-hoc solutions further below.</em></p>\n\n<p>If you use an HotSpot JVM, since Java 6 update 21, you can use this command-line option:</p>\n\n<pre><code>-XX:+UseCompressedStrings\n</code></pre>\n\n<p>The <a href=\"http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html\" rel=\"nofollow noreferrer\">JVM Options</a> page reads:</p>\n\n<blockquote>\n <p>Use a byte[] for Strings which can be represented as pure ASCII. (Introduced\n in Java 6 Update 21 Performance Release)</p>\n</blockquote>\n\n<p><strong>UPDATE</strong>: This feature was broken in a later version and was supposed to be fixed again in Java SE 6u25 as mentioned by the <a href=\"http://download.java.net/jdk6/6u25/promoted/b03/changes/JDK6u25.b03.list.html\" rel=\"nofollow noreferrer\">6u25 b03 release notes</a> (however we don't see it in the <a href=\"http://www.oracle.com/technetwork/java/javase/2col/6u25bugfixes-356453.html\" rel=\"nofollow noreferrer\">6u25 final release notes</a>). The <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7016213\" rel=\"nofollow noreferrer\">bug report 7016213</a> is not visible for security reasons. So, use with care and check first. Like any <code>-XX</code> option, it is deemed experimental and subject to change without much notice, so it's probably not always best to not use that in the startup scrip of a production server.</p>\n\n<p><strong>UPDATE 2013-03</strong> <em>(thanks to a comment by <a href=\"https://stackoverflow.com/users/1073844/aleksey-maximus\">Aleksey Maximus</a>)</em>: See this <a href=\"https://stackoverflow.com/questions/8833385/is-support-for-compressed-strings-being-dropped\">related question</a> and <a href=\"https://stackoverflow.com/a/10289995/453590\">its accepted answer</a>. The option now seems to be deceased. This is further confirmed in the bug <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7129417\" rel=\"nofollow noreferrer\">7129417</a> report.</p>\n\n<h1>The End Justifies the Means</h1>\n\n<p><em><strong>Warning:</strong> (Ugly) Solutions for Specific Needs</em></p>\n\n<p><em>This is a bit out of the box and lower-level, but since you asked... don't hit the messenger!</em></p>\n\n<h2>Your Own Lighter String Representation</h2>\n\n<p>If ASCII is fine for you needs, then why don't you just roll out your own implementation?</p>\n\n<p>As you mentioned, you could <code>byte[]</code> instead of <code>char[]</code> internally. But that's not all.</p>\n\n<p>To do it even more lightweight, instead of wrapping your byte arrays in a class, why not simply use an helper class containing mostly static methods operating on these byte arrays that you pass around? Sure, it's going to feel pretty C-ish, but it would work, and would save you the <strong>huge</strong> overhead that goes with <code>String</code> objects.</p>\n\n<p>And sure, it would miss some nice functionalities... unless your re-implement them. If you really need them, then there's not much choice. Thanks to OpenJDK and a lot of other good projects, you could very well roll out your own fugly <code>LiteStrings</code> class that just operate on <code>byte[]</code> parameters. You'll feel like taking a shower every time you need to call a function, but you'll have saved heaps of memory.</p>\n\n<p>I'd recommend to make it resemble closely the <code>String</code> class's contract and to provide meaningful adapters and builders to convert from and to <code>String</code>, and you might want to also have adapters to and from <code>StringBuffer</code> and <code>StringBuilder</code>, as well as some mirror implementations of other things you might need. Definitely some piece of work, but might be worth it (see a bit below the \"Make it Count!\" section).</p>\n\n<h2>On-the-Fly Compression/Decompression</h2>\n\n<p>You could very well compress your strings in memory and decompress them on the fly when you need them. After all, you only need to be able to read them when you access them, right?</p>\n\n<p>Of course, being that violent will mean:</p>\n\n<ul>\n<li>more complex (thus less maintainable) code,</li>\n<li>more processing power,</li>\n<li>relatively long strings are needed for the compression to be relevant (or to compact multiple strings into one by implementing your own store system, to make the compression more effective).</li>\n</ul>\n\n<h2>Do Both</h2>\n\n<p>For a full-headache, of course you can do all of that:</p>\n\n<ul>\n<li>C-ish helper class,</li>\n<li>byte arrays,</li>\n<li>on-the-fly compressed store.</li>\n</ul>\n\n<p><em>Be sure to make that open-source. :)</em></p>\n\n<h1>Make it Count!</h1>\n\n<p><em>By the way, see this great presentation on <strong>Building Memory-Efficient Java Applications</strong> by N. Mitchell and G. Sevitsky: [<a href=\"http://domino.research.ibm.com/comm/research_people.nsf/pages/sevitsky.pubs.html/$FILE/oopsla08%20memory-efficient%20java%20slides.pdf\" rel=\"nofollow noreferrer\">2008 version</a>], [<a href=\"http://www.cs.virginia.edu/kim/publicity/pldi09tutorials/memory-efficient-java-tutorial.pdf\" rel=\"nofollow noreferrer\">2009 version</a>].</em></p>\n\n<p>From this presentation, we see that an <strong>8-char string eats 64 bytes</strong> on a 32-bit system (96 for a 64-bit system!!), and most of it is due to JVM overhead. And from this <a href=\"http://www.javamex.com/tutorials/memory/array_memory_usage.shtml\" rel=\"nofollow noreferrer\">article</a> we see that an <strong>8-byte array would eat \"only\" 24 bytes</strong>: 12 bytes of header, 8 x 1 byte + 4 bytes of alignment).</p>\n\n<p>Sounds like this could be worth it if you really manipulate a lot of that stuff (and possibly speed up things a bit, as you'd spend less time allocating memory, but don't quote me on that and benchmark it; plus it would depend greatly on your implementation).</p>\n"
},
{
"answer_id": 8349470,
"author": "Axl",
"author_id": 16605,
"author_profile": "https://Stackoverflow.com/users/16605",
"pm_score": 1,
"selected": false,
"text": "<p>The UseCompressedStrings compiler option seems like the easiest route to take. If you're using strings only for storage, and not doing any equals/substring/split operations, then something like this CompactCharSequence class could work:</p>\n\n<p><a href=\"http://www.javamex.com/tutorials/memory/ascii_charsequence.shtml\" rel=\"nofollow\">http://www.javamex.com/tutorials/memory/ascii_charsequence.shtml</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21368/"
] |
After reading [this old article](http://www.javaworld.com/javaworld/javatips/jw-javatip130.html?page=2) measuring the memory consumption of several object types, I was amazed to see how much memory `String`s use in Java:
```
length: 0, {class java.lang.String} size = 40 bytes
length: 7, {class java.lang.String} size = 56 bytes
```
While the article has some tips to minimize this, I did not find them entirely satisfying. It seems to be wasteful to use `char[]` for storing the data. The obvious improvement for most western languages would be to use `byte[]` and an encoding like UTF-8 instead, as you only need a single byte to store the most frequent characters then instead of two bytes.
Of course one could use `String.getBytes("UTF-8")` and `new String(bytes, "UTF-8")`. Even the overhead of the String instance itself would be gone. But then there you lose very handy methods like `equals()`, `hashCode()`, `length()`, ...
Sun has a [patent](http://www.freepatentsonline.com/6751790.html) on `byte[]` representation of Strings, as far as I can tell.
>
> **Frameworks for efficient representation of string objects in Java programming environments**
>
> ... The techniques can be implemented to create Java string objects as arrays of one-byte characters when it is appropriate ...
>
>
>
But I failed to find an API for that patent.
Why do I care?
In most cases I don't. But I worked on applications with huge caches, containing lots of Strings, which would have benefitted from using the memory more efficiently.
Does anybody know of such an API? Or is there another way to keep your memory footprint for Strings small, even at the cost of CPU performance or uglier API?
Please don't repeat the suggestions from the above article:
* own variant of `String.intern()` (possibly with `SoftReferences`)
* storing a single `char[]` and exploiting the current `String.subString(.)` implementation to avoid data copying (nasty)
**Update**
I ran the code from the article on Sun's current JVM (1.6.0\_10). It yielded the same results as in 2002.
|
With a Little Bit of Help From the JVM...
=========================================
***WARNING:** This solution is now obsolete in newer Java SE versions. See other ad-hoc solutions further below.*
If you use an HotSpot JVM, since Java 6 update 21, you can use this command-line option:
```
-XX:+UseCompressedStrings
```
The [JVM Options](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html) page reads:
>
> Use a byte[] for Strings which can be represented as pure ASCII. (Introduced
> in Java 6 Update 21 Performance Release)
>
>
>
**UPDATE**: This feature was broken in a later version and was supposed to be fixed again in Java SE 6u25 as mentioned by the [6u25 b03 release notes](http://download.java.net/jdk6/6u25/promoted/b03/changes/JDK6u25.b03.list.html) (however we don't see it in the [6u25 final release notes](http://www.oracle.com/technetwork/java/javase/2col/6u25bugfixes-356453.html)). The [bug report 7016213](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7016213) is not visible for security reasons. So, use with care and check first. Like any `-XX` option, it is deemed experimental and subject to change without much notice, so it's probably not always best to not use that in the startup scrip of a production server.
**UPDATE 2013-03** *(thanks to a comment by [Aleksey Maximus](https://stackoverflow.com/users/1073844/aleksey-maximus))*: See this [related question](https://stackoverflow.com/questions/8833385/is-support-for-compressed-strings-being-dropped) and [its accepted answer](https://stackoverflow.com/a/10289995/453590). The option now seems to be deceased. This is further confirmed in the bug [7129417](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7129417) report.
The End Justifies the Means
===========================
***Warning:** (Ugly) Solutions for Specific Needs*
*This is a bit out of the box and lower-level, but since you asked... don't hit the messenger!*
Your Own Lighter String Representation
--------------------------------------
If ASCII is fine for you needs, then why don't you just roll out your own implementation?
As you mentioned, you could `byte[]` instead of `char[]` internally. But that's not all.
To do it even more lightweight, instead of wrapping your byte arrays in a class, why not simply use an helper class containing mostly static methods operating on these byte arrays that you pass around? Sure, it's going to feel pretty C-ish, but it would work, and would save you the **huge** overhead that goes with `String` objects.
And sure, it would miss some nice functionalities... unless your re-implement them. If you really need them, then there's not much choice. Thanks to OpenJDK and a lot of other good projects, you could very well roll out your own fugly `LiteStrings` class that just operate on `byte[]` parameters. You'll feel like taking a shower every time you need to call a function, but you'll have saved heaps of memory.
I'd recommend to make it resemble closely the `String` class's contract and to provide meaningful adapters and builders to convert from and to `String`, and you might want to also have adapters to and from `StringBuffer` and `StringBuilder`, as well as some mirror implementations of other things you might need. Definitely some piece of work, but might be worth it (see a bit below the "Make it Count!" section).
On-the-Fly Compression/Decompression
------------------------------------
You could very well compress your strings in memory and decompress them on the fly when you need them. After all, you only need to be able to read them when you access them, right?
Of course, being that violent will mean:
* more complex (thus less maintainable) code,
* more processing power,
* relatively long strings are needed for the compression to be relevant (or to compact multiple strings into one by implementing your own store system, to make the compression more effective).
Do Both
-------
For a full-headache, of course you can do all of that:
* C-ish helper class,
* byte arrays,
* on-the-fly compressed store.
*Be sure to make that open-source. :)*
Make it Count!
==============
*By the way, see this great presentation on **Building Memory-Efficient Java Applications** by N. Mitchell and G. Sevitsky: [[2008 version](http://domino.research.ibm.com/comm/research_people.nsf/pages/sevitsky.pubs.html/$FILE/oopsla08%20memory-efficient%20java%20slides.pdf)], [[2009 version](http://www.cs.virginia.edu/kim/publicity/pldi09tutorials/memory-efficient-java-tutorial.pdf)].*
From this presentation, we see that an **8-char string eats 64 bytes** on a 32-bit system (96 for a 64-bit system!!), and most of it is due to JVM overhead. And from this [article](http://www.javamex.com/tutorials/memory/array_memory_usage.shtml) we see that an **8-byte array would eat "only" 24 bytes**: 12 bytes of header, 8 x 1 byte + 4 bytes of alignment).
Sounds like this could be worth it if you really manipulate a lot of that stuff (and possibly speed up things a bit, as you'd spend less time allocating memory, but don't quote me on that and benchmark it; plus it would depend greatly on your implementation).
|
231,052 |
<p>I have a page where a few textboxes cannot be empty before clicking a Save button. </p>
<pre><code><TextBox...
<TextBox.Text>
<Binding Path ="LastName" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:StringRequiredValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</code></pre>
<p>My rule works, I have a red border around my textbox until I enter a value. I now want to add this validation rule to my other text boxes.</p>
<p>How do I disable the Save button until the page has no validation errors? I'm not sure what to check.</p>
|
[
{
"answer_id": 232548,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 3,
"selected": false,
"text": "<p>You want to use <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.haserror.aspx\" rel=\"noreferrer\">Validation.HasError</a> attached property.</p>\n\n<p>Along the same lines Josh Smith has an interesting read on <a href=\"http://joshsmithonwpf.wordpress.com/2008/10/08/binding-to-validationerrors0-without-creating-debug-spew/\" rel=\"noreferrer\">Binding to (Validation.Errors)[0] without Creating Debug Spew</a>.</p>\n"
},
{
"answer_id": 808190,
"author": "Christoph",
"author_id": 98795,
"author_profile": "https://Stackoverflow.com/users/98795",
"pm_score": 4,
"selected": false,
"text": "<p>On the codebehind for the view you could wireup the Validation.ErrorEvent like so;</p>\n\n<pre><code>this.AddHandler(Validation.ErrorEvent,new RoutedEventHandler(OnErrorEvent)); \n</code></pre>\n\n<p>And then </p>\n\n<pre><code>private int errorCount;\nprivate void OnErrorEvent(object sender, RoutedEventArgs e)\n{\n var validationEventArgs = e as ValidationErrorEventArgs;\n if (validationEventArgs == null)\n throw new Exception(\"Unexpected event args\");\n switch(validationEventArgs.Action)\n {\n case ValidationErrorEventAction.Added:\n {\n errorCount++; break;\n }\n case ValidationErrorEventAction.Removed:\n {\n errorCount--; break;\n }\n default:\n {\n throw new Exception(\"Unknown action\");\n }\n }\n Save.IsEnabled = errorCount == 0;\n}\n</code></pre>\n\n<p>This makes the assumption that you will get notified of the removal (which won't happen if you remove the offending element while it is invalid).</p>\n"
},
{
"answer_id": 7512442,
"author": "Nihal",
"author_id": 958741,
"author_profile": "https://Stackoverflow.com/users/958741",
"pm_score": 2,
"selected": false,
"text": "<pre><code>int count = 0;\n\nprivate void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)\n{\n if (e.Action == ValidationErrorEventAction.Added)\n {\n button1.IsEnabled = false;\n count++;\n }\n if (e.Action == ValidationErrorEventAction.Removed)\n { \n count--;\n if (count == 0) button1.IsEnabled = true;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8157748,
"author": "andrey.tsykunov",
"author_id": 108317,
"author_profile": "https://Stackoverflow.com/users/108317",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a helper method which tracks validation errors on the dependency objects (and all its children) and calls delegate to notify about the change. It also tracks removal of the children with validation errors.</p>\n\n<pre><code> public static void AddErrorHandler(DependencyObject element, Action<bool> setHasValidationErrors)\n {\n var errors = new List<Tuple<object, ValidationError>>();\n\n RoutedEventHandler sourceUnloaded = null;\n\n sourceUnloaded = (sender, args) =>\n {\n if (sender is FrameworkElement)\n ((FrameworkElement) sender).Unloaded -= sourceUnloaded;\n else\n ((FrameworkContentElement) sender).Unloaded -= sourceUnloaded;\n\n foreach (var error in errors.Where(err => err.Item1 == sender).ToArray())\n errors.Remove(error);\n\n setHasValidationErrors(errors.Any());\n };\n\n EventHandler<ValidationErrorEventArgs> errorHandler = (_, args) =>\n {\n if (args.Action == ValidationErrorEventAction.Added)\n {\n errors.Add(new Tuple<object, ValidationError>(args.OriginalSource, args.Error));\n\n if (args.OriginalSource is FrameworkElement)\n ((FrameworkElement)args.OriginalSource).Unloaded += sourceUnloaded;\n else if (args.OriginalSource is FrameworkContentElement)\n ((FrameworkContentElement)args.OriginalSource).Unloaded += sourceUnloaded;\n }\n else\n {\n var error = errors\n .FirstOrDefault(err => err.Item1 == args.OriginalSource && err.Item2 == args.Error);\n\n if (error != null) \n errors.Remove(error);\n }\n\n setHasValidationErrors(errors.Any());\n };\n\n\n System.Windows.Controls.Validation.AddErrorHandler(element, errorHandler);\n } \n</code></pre>\n"
},
{
"answer_id": 8975839,
"author": "NoWar",
"author_id": 196919,
"author_profile": "https://Stackoverflow.com/users/196919",
"pm_score": 5,
"selected": true,
"text": "<p>Here is the complete sample what you need.</p>\n\n<p><a href=\"http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/\" rel=\"noreferrer\">http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/</a></p>\n\n<p><a href=\"https://skydrive.live.com/?cid=2c6600f1c1d5e3be&id=2C6600F1C1D5E3BE%21203\" rel=\"noreferrer\">https://skydrive.live.com/?cid=2c6600f1c1d5e3be&id=2C6600F1C1D5E3BE%21203</a></p>\n\n<p><img src=\"https://i.stack.imgur.com/wRAT1.jpg\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 14030269,
"author": "Bilal",
"author_id": 1928121,
"author_profile": "https://Stackoverflow.com/users/1928121",
"pm_score": 2,
"selected": false,
"text": "<p>this is it \nyou need to check the HasError control property from the code behaind </p>\n\n<p>and do this code in the save button click </p>\n\n<pre><code> BindingExpression bexp = this.TextBox1.GetBindingExpression(TextBox.TextProperty);\nbexp.UpdateSource(); // this to refresh the binding and see if any error exist \nbool hasError = bexp.HasError; // this is boolean property indique if there is error \n\nMessageBox.Show(hasError.ToString());\n</code></pre>\n"
},
{
"answer_id": 26485326,
"author": "Alexander Sirotkin",
"author_id": 4165577,
"author_profile": "https://Stackoverflow.com/users/4165577",
"pm_score": 1,
"selected": false,
"text": "<p>just inhert your ViewModel from System.ComponentModel.IDataErrorInfo for Validate\nand from INotifyPropertyChanged to notify button</p>\n\n<p>make property:</p>\n\n<pre><code> public bool IsValid\n {\n get\n {\n if (this.FloorPlanName.IsEmpty())\n return false;\n return true;\n }\n }\n</code></pre>\n\n<p>in xaml, connect it to button</p>\n\n<pre><code><Button Margin=\"4,0,0,0\" Style=\"{StaticResource McVMStdButton_Ok}\" Click=\"btnDialogOk_Click\" IsEnabled=\"{Binding IsValid}\"/>\n</code></pre>\n\n<p>in the IDataErrorInfo overrides, notify btutton</p>\n\n<pre><code>public string this[string columnName]{\n get\n {\n switch (columnName)\n {\n case \"FloorPlanName\":\n if (this.FloorPlanName.IsEmpty())\n {\n OnPropertyChanged(\"IsValid\");\n return \"Floor plan name cant be empty\";\n }\n break;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 34953774,
"author": "Kabua",
"author_id": 1067299,
"author_profile": "https://Stackoverflow.com/users/1067299",
"pm_score": 1,
"selected": false,
"text": "<p>I've tried several of the solutions stated above; however, none of them worked for me.</p>\n<h3>My Simple Problem</h3>\n<p>I have a simple input window that request a URI from the user, if the <code>TextBox</code> value isn't a valid <code>Uri</code> then the <code>Okay</code> button should be disabled.</p>\n<h3>My Simple Solution</h3>\n<p>Here is what worked for me:</p>\n<pre><code>CommandBindings.Add(new CommandBinding(AppCommands.Okay,\n (sender, args) => DialogResult = true,\n (sender, args) => args.CanExecute = !(bool) _uriTextBoxControl.GetValue(Validation.HasErrorProperty)));\n</code></pre>\n"
},
{
"answer_id": 57160112,
"author": "Gregor A. Lamche",
"author_id": 460732,
"author_profile": "https://Stackoverflow.com/users/460732",
"pm_score": 2,
"selected": false,
"text": "<p>Because it's still missing, here is an adaption of Developer's answer in case the link ever goes away:</p>\n\n<p>XAML:</p>\n\n<pre><code><TextBox.Text Validation.Error=\"handleValidationError\">\n <Binding Path =\"LastName\" \n UpdateSourceTrigger=\"PropertyChanged\"\n NotifyOnValidationError=\"True\">\n <Binding.ValidationRules>\n <local:StringRequiredValidationRule />\n </Binding.ValidationRules> \n </Binding>\n</TextBox.Text>\n<Button IsEnabled=\"{Binding HasNoValidationErrors}\"/>\n</code></pre>\n\n<p>CodeBehind/C#:</p>\n\n<pre><code>private int _numberOfValidationErrors;\npublic bool HasNoValidationErrors => _numberOfValidationErrors = 0;\n\nprivate void handleValidationError(object sender, ValidationErrorEventArgs e)\n{\n if (e.Action == ValidationErrorEventAction.Added)\n _numberOfValidationErrors++;\n else\n _numberOfValidationErrors--;\n}\n</code></pre>\n"
},
{
"answer_id": 59771649,
"author": "David Shader",
"author_id": 10641390,
"author_profile": "https://Stackoverflow.com/users/10641390",
"pm_score": 0,
"selected": false,
"text": "<p>This website has the code you're looking for:\n<a href=\"https://www.wpfsharp.com/2012/02/03/how-to-disable-a-button-on-textbox-validationerrors-in-wpf/\" rel=\"nofollow noreferrer\">https://www.wpfsharp.com/2012/02/03/how-to-disable-a-button-on-textbox-validationerrors-in-wpf/</a></p>\n\n<p>For posterity the button code should look like this if you are using a ValidationRule override on the input fields:</p>\n\n<pre><code><Button Content=\"<NameThisButton>\" Click=\"<MethodToCallOnClick>\" >\n <Button.Style>\n <Style TargetType=\"{x:Type Button}\">\n <Setter Property=\"IsEnabled\" Value=\"false\" />\n <Style.Triggers>\n <MultiDataTrigger>\n <MultiDataTrigger.Conditions> \n <Condition Binding=\"{Binding ElementName=<TextBoxName>, Path=(Validation.HasError)}\" Value=\"false\" />\n <Condition Binding=\"{Binding ElementName=<TextBoxName>, Path=(Validation.HasError)}\" Value=\"false\" />\n </MultiDataTrigger.Conditions>\n <Setter Property=\"IsEnabled\" Value=\"true\" />\n </MultiDataTrigger>\n </Style.Triggers>\n </Style>\n </Button.Style>\n </Button>\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
I have a page where a few textboxes cannot be empty before clicking a Save button.
```
<TextBox...
<TextBox.Text>
<Binding Path ="LastName" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:StringRequiredValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
```
My rule works, I have a red border around my textbox until I enter a value. I now want to add this validation rule to my other text boxes.
How do I disable the Save button until the page has no validation errors? I'm not sure what to check.
|
Here is the complete sample what you need.
<http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/>
<https://skydrive.live.com/?cid=2c6600f1c1d5e3be&id=2C6600F1C1D5E3BE%21203>

|
231,057 |
<p>Is there any library function for this purpose, so I don't do it by hand and risk ending in TDWTF?</p>
<pre><code>echo ceil(31497230840470473074370324734723042.6);
// Expected result
31497230840470473074370324734723043
// Prints
<garbage>
</code></pre>
|
[
{
"answer_id": 231171,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "<p>This will work for you:</p>\n\n<pre><code>$x = '31497230840470473074370324734723042.9';\n\nbcscale(100);\nvar_dump(bcFloor($x));\nvar_dump(bcCeil($x));\nvar_dump(bcRound($x));\n\nfunction bcFloor($x)\n{\n $result = bcmul($x, '1', 0);\n if ((bccomp($result, '0', 0) == -1) && bccomp($x, $result, 1))\n $result = bcsub($result, 1, 0);\n\n return $result;\n}\n\nfunction bcCeil($x)\n{\n $floor = bcFloor($x);\n return bcadd($floor, ceil(bcsub($x, $floor)), 0);\n}\n\nfunction bcRound($x)\n{\n $floor = bcFloor($x);\n return bcadd($floor, round(bcsub($x, $floor)), 0);\n}\n</code></pre>\n\n<p>Basically it finds the flooy by multiplying by one with zero precision.</p>\n\n<p>Then it can do ceil / round by subtracting that from the total, calling the built in functions, then adding the result back on</p>\n\n<p>Edit: fixed for -ve numbers</p>\n"
},
{
"answer_id": 1653830,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 4,
"selected": false,
"text": "<p><strong>UPDATE: See my improved answer here: <a href=\"https://stackoverflow.com/questions/1642614/how-to-ceil-floor-and-round-bcmath-numbers/1653826#1653826\">How to ceil, floor and round bcmath numbers?</a>.</strong></p>\n\n<hr>\n\n<p>These functions seem to make more sense, at least to me:</p>\n\n<pre><code>function bcceil($number)\n{\n if ($number[0] != '-')\n {\n return bcadd($number, 1, 0);\n }\n\n return bcsub($number, 0, 0);\n}\n\nfunction bcfloor($number)\n{\n if ($number[0] != '-')\n {\n return bcadd($number, 0, 0);\n }\n\n return bcsub($number, 1, 0);\n}\n\nfunction bcround($number, $precision = 0)\n{\n if ($number[0] != '-')\n {\n return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);\n }\n\n return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);\n}\n</code></pre>\n\n<p><strong>They support negative numbers and the precision argument for the bcround() function.</strong></p>\n\n<p>Some tests:</p>\n\n<pre><code>assert(bcceil('4.3') == ceil('4.3')); // true\nassert(bcceil('9.999') == ceil('9.999')); // true\nassert(bcceil('-3.14') == ceil('-3.14')); // true\n\nassert(bcfloor('4.3') == floor('4.3')); // true\nassert(bcfloor('9.999') == floor('9.999')); // true\nassert(bcfloor('-3.14') == floor('-3.14')); // true\n\nassert(bcround('3.4', 0) == number_format('3.4', 0)); // true\nassert(bcround('3.5', 0) == number_format('3.5', 0)); // true\nassert(bcround('3.6', 0) == number_format('3.6', 0)); // true\nassert(bcround('1.95583', 2) == number_format('1.95583', 2)); // true\nassert(bcround('5.045', 2) == number_format('5.045', 2)); // true\nassert(bcround('5.055', 2) == number_format('5.055', 2)); // true\nassert(bcround('9.999', 2) == number_format('9.999', 2)); // true\n</code></pre>\n"
},
{
"answer_id": 55606171,
"author": "Theodore R. Smith",
"author_id": 430062,
"author_profile": "https://Stackoverflow.com/users/430062",
"pm_score": 0,
"selected": false,
"text": "<p>OK, for my <a href=\"https://github.com/phpexpertsinc/MoneyType\" rel=\"nofollow noreferrer\"><strong>high-precision Money library</strong></a>, which is currently on hundreds of production sites, I had to completely rewrite this bcround functionality. Nothing I found on the entire Internet was up to code.</p>\n\n<p>Here's what I came up with:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Based off of https://stackoverflow.com/a/1653826/430062\n * Thanks, [Alix Axel](https://stackoverflow.com/users/89771/alix-axel)!\n *\n * @param $number\n * @param int $precision\n * @return string\n */\nfunction bcround($number, $precision = BCMathCalcStrategy::PRECISION)\n{\n if (strpos($number, '.') !== false) {\n if ($number[0] != '-') return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);\n return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);\n }\n\n // Pad it out to the desired precision.\n return number_format($number, $precision);\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13211/"
] |
Is there any library function for this purpose, so I don't do it by hand and risk ending in TDWTF?
```
echo ceil(31497230840470473074370324734723042.6);
// Expected result
31497230840470473074370324734723043
// Prints
<garbage>
```
|
This will work for you:
```
$x = '31497230840470473074370324734723042.9';
bcscale(100);
var_dump(bcFloor($x));
var_dump(bcCeil($x));
var_dump(bcRound($x));
function bcFloor($x)
{
$result = bcmul($x, '1', 0);
if ((bccomp($result, '0', 0) == -1) && bccomp($x, $result, 1))
$result = bcsub($result, 1, 0);
return $result;
}
function bcCeil($x)
{
$floor = bcFloor($x);
return bcadd($floor, ceil(bcsub($x, $floor)), 0);
}
function bcRound($x)
{
$floor = bcFloor($x);
return bcadd($floor, round(bcsub($x, $floor)), 0);
}
```
Basically it finds the flooy by multiplying by one with zero precision.
Then it can do ceil / round by subtracting that from the total, calling the built in functions, then adding the result back on
Edit: fixed for -ve numbers
|
231,069 |
<p>I want to write a default structure, N times, to a file, using fwrite.</p>
<pre><code>typedef struct foo_s {
uint32 A;
uint32 B;
char desc[100];
}foo_t;
void init_file(FILE *fp, int N)
{
foo_t foo_struct = {0};
foo_struct.A = -1;
foo_struct.B = 1;
fwrite(&foo_struct, sizeof(foo_struct), N, fp); }
</code></pre>
<p>The above code does not write foo_struct N times to the file stream fp.</p>
<p>Instead it writes N*sizeof(foo_struct) bytes starting from &foo_struct to fp. </p>
<p>Can anyone tell how to achieve the same with a single fwrite?</p>
|
[
{
"answer_id": 231083,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 2,
"selected": false,
"text": "<p>The only way to do this with a single fwrite is to replicate the foo_struct N times in RAM, then do a single fwrite of all that RAM.</p>\n\n<p>I doubt that doing a malloc, N copies, and then an fwrite would be quicker than just doing N fwrites (this is the only reason I can think of for wanting to do this!), but if you really care, you should try it.</p>\n"
},
{
"answer_id": 231084,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": true,
"text": "<p>You can't with a single fwrite(). You'd have to use a loop:</p>\n\n<pre><code>int i;\nfor (i = 0; i < N; ++i)\n fwrite(&foo_struct, sizeof(foo_struct), 1, fp);\n</code></pre>\n\n<p>The third parameter of fwrite() is the number of objects to write, not the number of times to write a single object.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29405/"
] |
I want to write a default structure, N times, to a file, using fwrite.
```
typedef struct foo_s {
uint32 A;
uint32 B;
char desc[100];
}foo_t;
void init_file(FILE *fp, int N)
{
foo_t foo_struct = {0};
foo_struct.A = -1;
foo_struct.B = 1;
fwrite(&foo_struct, sizeof(foo_struct), N, fp); }
```
The above code does not write foo\_struct N times to the file stream fp.
Instead it writes N\*sizeof(foo\_struct) bytes starting from &foo\_struct to fp.
Can anyone tell how to achieve the same with a single fwrite?
|
You can't with a single fwrite(). You'd have to use a loop:
```
int i;
for (i = 0; i < N; ++i)
fwrite(&foo_struct, sizeof(foo_struct), 1, fp);
```
The third parameter of fwrite() is the number of objects to write, not the number of times to write a single object.
|
231,098 |
<p>I'd like a loop that uses a UInt16 (ushort) to loop through all of its values. However, this doesn't do it:</p>
<pre><code>for( ushort i = 0; i < UInt16.MaxValue; i++ )
{
// do something
}
</code></pre>
<p>The problem is that the loop will quit when i == 0xFFFF and not "do something".
If I change the 'for' statement to "for(ushort i = 0; i <= UInt16.MaxValue; i++ )", then it becomes an infinite loop because i never gets to 0x10000 because ushorts only go to 0xFFFF.</p>
<p>I could make 'i' an int and cast it or assign it to a ushort variable in the loop.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 231112,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 5,
"selected": true,
"text": "<p>Use a <code>do...while</code> loop</p>\n\n<pre><code>ushort i = 0;\ndo\n{\n // do something\n} while(i++ < UInt16.MaxValue);\n</code></pre>\n\n<p>There is an interesting discussion of testing loops at the top vs. the bottom <a href=\"https://stackoverflow.com/questions/224059/do-your-loops-test-at-the-top-or-bottom\">here</a>.</p>\n"
},
{
"answer_id": 231114,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 2,
"selected": false,
"text": "<p>You could simply replace the for by a do-while loop.</p>\n\n<pre><code>ushort i = 0;\ndo\n{\ni++;\n...\n} while(i!=UInt16.MaxValue);\n</code></pre>\n"
},
{
"answer_id": 231188,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.uint16.maxvalue.aspx\" rel=\"nofollow noreferrer\"><code>UInt16.MaxValue</code> evaluates to <code>0xffff</code></a>, not <code>0x10000</code>. I think you can do this with a <code>do</code>/<code>while</code> loop, as a variation on burkhard1979's answer.</p>\n\n<pre><code>ushort i = 0;\ndo {\n ...\n} while (++i != 0);\n</code></pre>\n"
},
{
"answer_id": 231252,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 1,
"selected": false,
"text": "<p>does it have to be a short? why not just</p>\n\n<pre><code>for(int i = 0;i<=0xFFFF;i++)\n{\n //do whatever\n}\n</code></pre>\n"
},
{
"answer_id": 231332,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming that your code suffers from an off by one error (the current code, stops just before having the final value evaluated. Then the following might answer you.</p>\n\n<p>Very simple, as your counter is a 16 bit unsigned integer, it can not have values bigger than <code>0xffff</code>, as that value is still valid, you need to have some value that extends beyond that as the guard. However adding <code>1</code> to <code>0xffff</code> in 16 bits just wraps around to <code>0</code>. As suggested, either use a do while loop (that does not need a guard value), or use a larger value to contain your counter.</p>\n\n<p>ps. Using 16 bit variables on modern machines is actually less efficient than using 32 bit variables as no overflow code needs to be generated.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9516/"
] |
I'd like a loop that uses a UInt16 (ushort) to loop through all of its values. However, this doesn't do it:
```
for( ushort i = 0; i < UInt16.MaxValue; i++ )
{
// do something
}
```
The problem is that the loop will quit when i == 0xFFFF and not "do something".
If I change the 'for' statement to "for(ushort i = 0; i <= UInt16.MaxValue; i++ )", then it becomes an infinite loop because i never gets to 0x10000 because ushorts only go to 0xFFFF.
I could make 'i' an int and cast it or assign it to a ushort variable in the loop.
Any suggestions?
|
Use a `do...while` loop
```
ushort i = 0;
do
{
// do something
} while(i++ < UInt16.MaxValue);
```
There is an interesting discussion of testing loops at the top vs. the bottom [here](https://stackoverflow.com/questions/224059/do-your-loops-test-at-the-top-or-bottom).
|
231,126 |
<p>I'm terribly new to SQL, and cannot seem to get the desired information out, after trying a few different google searches, and reading through some SQL tutorials.</p>
<p>I think it involves some sort of joins, but cannot get them straight.</p>
<p>Given the following sample tables:</p>
<p>Table 1(Activity This is updated every time a change is made to a task, could be manytimes per day):</p>
<pre><code>ID Who What When
001 John Created 2008-10-01<br>
001 Bill Closed 2008-10-02<br>
001 John Updated 2008-10-03<br>
002 Bill Created 2008-10-04<br>
002 John Updated 2008-10-05<br>
002 Bill Closed 2008-10-06<br>
</code></pre>
<p>Table 2(Tasks - This is the main task tracking table):</p>
<pre><code>ID Created Status
001 2008-10-01 Closed
002 2008-10-04 Closed
</code></pre>
<p>Table 3(Comments):</p>
<pre><code>ID When Comment<br
001 2008-10-01 "I'm creating a new task"
001 2008-10-02 "I have completed the task"
001 2008-10-03 "Nice job"
002 2008-10-04 "I'm creating a second task"
002 2008-10-05 "This task looks too easy"
002 2008-10-06 "I have completed this easy task"
</code></pre>
<p>What SQL (mySQL if it makes any difference) query would I use to find out who had done something on a task that had been closed?</p>
<p>The results would be something like:</p>
<pre><code>Who What ID When Comment
Bill Updated 002 2008-10-03 "Nice job"
</code></pre>
<p>Meaning that Bill changed task 002 after it was closed, and added the comment "Nice Job"</p>
<p>Any help would be much appreciated.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 231139,
"author": "Totty",
"author_id": 30838,
"author_profile": "https://Stackoverflow.com/users/30838",
"pm_score": 2,
"selected": false,
"text": "<p>You will need to use a JOIN statement to retrieve fields from multiple tables.\n<a href=\"http://www.w3schools.com/Sql/sql_join.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/Sql/sql_join.asp</a></p>\n\n<pre><code>SELECT Activity.Who, Activity.What, Comments.When, Comments.Comment FROM Activity JOIN Comments ON Activity.ID = Comments.ID JOIN Tasks ON Comments.ID = Tasks.ID WHERE Tasks.Status = 'Closed'\n</code></pre>\n\n<p>Also, you're table structure looks to have a little redundancy.</p>\n"
},
{
"answer_id": 231154,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "<p>Are you planning on joining the tables based on the date? So you will only have 1 change per day?</p>\n"
},
{
"answer_id": 231387,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "<pre><code>SELECT a1.Who, a1.What, a1.ID, c.When, c.Comment\nFROM Activity AS a1\n JOIN Activity AS a2 ON (a1.ID = a2.ID AND a1.When > a2.When)\n JOIN Comments AS c ON (a1.ID = c.ID AND a.When = c.When);\nWHERE a2.What = 'Closed';\n</code></pre>\n\n<p>I think you need some way to associate a row in Comments to the correct row in Activity. Right now if two people comment on a given Task on the same day, you don't know whose comment is whose. I'd recommend that you give each row in Activity a unique key, and then reference that from the Comments table.</p>\n\n<pre><code>CREATE TABLE Tasks (\n Task_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n Created DATE NOT NULL,\n Status VARCHAR(10)\n) TYPE=InnoDB;\n\nCREATE TABLE Activity (\n Activity_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n Task_ID INT NOT NULL REFERENCES Tasks,\n Who VARCHAR(10) NOT NULL,\n What VARCHAR(10) NOT NULL,\n When DATE NOT NULL\n) TYPE=InnoDB;\n\nCREATE TABLE Comments (\n Comment_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n Activity_ID INT NOT NULL REFERENCES Activity,\n Who VARCHAR(10) NOT NULL,\n When DATE NOT NULL,\n Comment VARCHAR(100) NOT NULL\n) TYPE=InnoDB;\n</code></pre>\n\n<p>Then you can make associations so the query returns more accurate results:</p>\n\n<pre><code>SELECT c.Who, a1.What, a1.Task_ID, c.When, c.Comment\nFROM Activity AS a1\n JOIN Activity AS a2 ON (a1.Task_ID = a2.Task_ID AND a1.When > a2.When)\n JOIN Comments AS c ON (a1.Activity_ID = c.Activity_ID);\nWHERE a2.What = 'Closed';\n</code></pre>\n\n<p>Make sure to use <code>TYPE=InnoDB</code> in MySQL because the default storage engine MyISAM doesn't support foreign key references.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30939/"
] |
I'm terribly new to SQL, and cannot seem to get the desired information out, after trying a few different google searches, and reading through some SQL tutorials.
I think it involves some sort of joins, but cannot get them straight.
Given the following sample tables:
Table 1(Activity This is updated every time a change is made to a task, could be manytimes per day):
```
ID Who What When
001 John Created 2008-10-01<br>
001 Bill Closed 2008-10-02<br>
001 John Updated 2008-10-03<br>
002 Bill Created 2008-10-04<br>
002 John Updated 2008-10-05<br>
002 Bill Closed 2008-10-06<br>
```
Table 2(Tasks - This is the main task tracking table):
```
ID Created Status
001 2008-10-01 Closed
002 2008-10-04 Closed
```
Table 3(Comments):
```
ID When Comment<br
001 2008-10-01 "I'm creating a new task"
001 2008-10-02 "I have completed the task"
001 2008-10-03 "Nice job"
002 2008-10-04 "I'm creating a second task"
002 2008-10-05 "This task looks too easy"
002 2008-10-06 "I have completed this easy task"
```
What SQL (mySQL if it makes any difference) query would I use to find out who had done something on a task that had been closed?
The results would be something like:
```
Who What ID When Comment
Bill Updated 002 2008-10-03 "Nice job"
```
Meaning that Bill changed task 002 after it was closed, and added the comment "Nice Job"
Any help would be much appreciated.
Thanks in advance.
|
```
SELECT a1.Who, a1.What, a1.ID, c.When, c.Comment
FROM Activity AS a1
JOIN Activity AS a2 ON (a1.ID = a2.ID AND a1.When > a2.When)
JOIN Comments AS c ON (a1.ID = c.ID AND a.When = c.When);
WHERE a2.What = 'Closed';
```
I think you need some way to associate a row in Comments to the correct row in Activity. Right now if two people comment on a given Task on the same day, you don't know whose comment is whose. I'd recommend that you give each row in Activity a unique key, and then reference that from the Comments table.
```
CREATE TABLE Tasks (
Task_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Created DATE NOT NULL,
Status VARCHAR(10)
) TYPE=InnoDB;
CREATE TABLE Activity (
Activity_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Task_ID INT NOT NULL REFERENCES Tasks,
Who VARCHAR(10) NOT NULL,
What VARCHAR(10) NOT NULL,
When DATE NOT NULL
) TYPE=InnoDB;
CREATE TABLE Comments (
Comment_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Activity_ID INT NOT NULL REFERENCES Activity,
Who VARCHAR(10) NOT NULL,
When DATE NOT NULL,
Comment VARCHAR(100) NOT NULL
) TYPE=InnoDB;
```
Then you can make associations so the query returns more accurate results:
```
SELECT c.Who, a1.What, a1.Task_ID, c.When, c.Comment
FROM Activity AS a1
JOIN Activity AS a2 ON (a1.Task_ID = a2.Task_ID AND a1.When > a2.When)
JOIN Comments AS c ON (a1.Activity_ID = c.Activity_ID);
WHERE a2.What = 'Closed';
```
Make sure to use `TYPE=InnoDB` in MySQL because the default storage engine MyISAM doesn't support foreign key references.
|
231,132 |
<p>I'm trying to get Wininet to ignore Internet Explorer's "Work Offline" mode, for both HTTP and FTP.</p>
<p>So I'm trying to use <code>InternetSetOption()</code> with <code>INTERNET_OPTION_IGNORE_OFFLINE</code>. The documentation says "This is used by <code>InternetQueryOption</code> and <code>InternetSetOption</code> with a request handle." However, you can't get a request handle because if IE is in Work Offline mode then <code>InternetConnect()</code> will always return a null handle. Without a connection handle you can't get a request handle. So I tried using it with an <code>InternetOpen()</code> handle and a <code>NULL</code> handle. Both failed with <code>ERROR_INTERNET_INCORRECT_HANDLE_TYPE</code>.</p>
<p>Is there a way to get this option to work? I found a reference on an MS newsgroup from 2003 that <code>INTERNET_OPEN_TYPE_PRECONFIG</code> is "broken". 5 years later with IE8 beta 2 and they still haven't fixed it? Or am I doing it wrong.</p>
<p><strong>Edit</strong><br/>
I wasn't quite correct. <code>InternetConnect()</code> always returns null if you are on "Work Offline" mode and using FTP, but it returns a valid handle if you are using Http. However, it still doesn't work even with a request handle.</p>
<p>If I am set to "Work Offline" and I call</p>
<pre><code>BOOL a = TRUE;
::InternetSetOption(hData, INTERNET_OPTION_IGNORE_OFFLINE, &a, sizeof(BOOL));
</code></pre>
<p>on the handle from </p>
<pre><code>HINTERNET hData = HttpOpenRequest(hInternet, L"POST", path, NULL, NULL, NULL, flags, 0 );
</code></pre>
<p>the <code>InternetSetOption()</code> call succeeds.<br>
However, the call to <code>HttpSendRequest()</code> still fails with error code 2 (file not found), same as it does if I don't set the option.<br>
Same thing if I call</p>
<pre><code>::InternetSetOption(hData, INTERNET_OPTION_IGNORE_OFFLINE, 0, 0);
</code></pre>
|
[
{
"answer_id": 471159,
"author": "michael",
"author_id": 31207,
"author_profile": "https://Stackoverflow.com/users/31207",
"pm_score": 0,
"selected": false,
"text": "<p>Did you tried <code>GET</code> instead of <code>POST</code> which sends additional data in headers? </p>\n\n<p>For example in REST-ful API POST request is equivalent to Create, Update, Delete and GET to Read and that might break the offline mode. Just guessing...</p>\n"
},
{
"answer_id": 5739763,
"author": "Rick Strahl",
"author_id": 11197,
"author_profile": "https://Stackoverflow.com/users/11197",
"pm_score": 1,
"selected": false,
"text": "<p>I checked use of <code>INTERNET_OPTION_IGNORE_OFFLINE</code> with the IE 9 version of WinInet and it does seem to work.</p>\n\n<p>Make sure you call InternetSetOption <em>before</em> you call HttpOpenRequest and pass in the hInternet handle instead. The option must be set before the request actually gets sent to the server. HttpOpenRequest</p>\n\n<p>+++ Rick ---</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24267/"
] |
I'm trying to get Wininet to ignore Internet Explorer's "Work Offline" mode, for both HTTP and FTP.
So I'm trying to use `InternetSetOption()` with `INTERNET_OPTION_IGNORE_OFFLINE`. The documentation says "This is used by `InternetQueryOption` and `InternetSetOption` with a request handle." However, you can't get a request handle because if IE is in Work Offline mode then `InternetConnect()` will always return a null handle. Without a connection handle you can't get a request handle. So I tried using it with an `InternetOpen()` handle and a `NULL` handle. Both failed with `ERROR_INTERNET_INCORRECT_HANDLE_TYPE`.
Is there a way to get this option to work? I found a reference on an MS newsgroup from 2003 that `INTERNET_OPEN_TYPE_PRECONFIG` is "broken". 5 years later with IE8 beta 2 and they still haven't fixed it? Or am I doing it wrong.
**Edit**
I wasn't quite correct. `InternetConnect()` always returns null if you are on "Work Offline" mode and using FTP, but it returns a valid handle if you are using Http. However, it still doesn't work even with a request handle.
If I am set to "Work Offline" and I call
```
BOOL a = TRUE;
::InternetSetOption(hData, INTERNET_OPTION_IGNORE_OFFLINE, &a, sizeof(BOOL));
```
on the handle from
```
HINTERNET hData = HttpOpenRequest(hInternet, L"POST", path, NULL, NULL, NULL, flags, 0 );
```
the `InternetSetOption()` call succeeds.
However, the call to `HttpSendRequest()` still fails with error code 2 (file not found), same as it does if I don't set the option.
Same thing if I call
```
::InternetSetOption(hData, INTERNET_OPTION_IGNORE_OFFLINE, 0, 0);
```
|
I checked use of `INTERNET_OPTION_IGNORE_OFFLINE` with the IE 9 version of WinInet and it does seem to work.
Make sure you call InternetSetOption *before* you call HttpOpenRequest and pass in the hInternet handle instead. The option must be set before the request actually gets sent to the server. HttpOpenRequest
+++ Rick ---
|
231,146 |
<p>I'm trying to change user input in wildcard form <code>("*word*")</code> to a regular expression format. To that end, I'm using the code below to strip off the <code>'*'</code> at the beginning and end of the input so that I can add the regular expression characters on either end:</p>
<pre><code>string::iterator iter_begin = expressionBuilder.begin();
string::iterator iter_end = expressionBuilder.end();
iter_end--;
if ((char)*iter_begin == '*' && (char)*iter_end == '*')
{
expressionBuilder.erase(iter_begin);
expressionBuilder.erase(iter_end);
expressionBuilder = "\\b\\w*" + expressionBuilder + "\\w*\\b";
}
</code></pre>
<p>However, the call to <code>"expressionBuilder.erase(iter_end)"</code> does <em>not</em> erase the trailing <code>'*'</code> from the input string so I wind up with an incorrect regular expression. What am I doing wrong here? <code>"(char)*iter_end == '*'"</code> must be true for the code inside the if statment to run (which it does), so why doesn't the same iterator work when passed to erase()?</p>
|
[
{
"answer_id": 231173,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": true,
"text": "<p>Try erasing them in the opposite order:</p>\n\n<pre><code>expressionBuilder.erase(iter_end);\nexpressionBuilder.erase(iter_begin);\n</code></pre>\n\n<p>After erasing the first *, iter_end refers to one character past the end of the string in your example. The <a href=\"http://www.sgi.com/tech/stl/basic_string.html\" rel=\"nofollow noreferrer\">STL documentation</a> indicates that iterators are invalidated by <code>erase()</code>, so technically my example is wrong too but I believe it will work in practice.</p>\n"
},
{
"answer_id": 231183,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 1,
"selected": false,
"text": "<p>(Revised, as I missed the <code>iter_end--</code> line).</p>\n\n<p>You probably want an if statement that only checks if <code>*iter_begin == '*'</code>, and then calls <code>find()</code> to get the other <code>'*'</code>. Or you could use <code>rbegin()</code> to get the \"beginning iterator of of the sequence in reverse,\" advance it one and then call <code>base()</code> to turn it to a regular iterator. That will get you the last character in the sequence.</p>\n\n<hr>\n\n<p>Even better, <code>std::string</code> has <a href=\"http://www.sgi.com/tech/stl/basic_string.html\" rel=\"nofollow noreferrer\"><code>rfind()</code> and <code>find_last_of()</code> methods</a>. They will get you the last <code>'*'</code>. You can also simply call <code>replace()</code> instead of stripping out the <code>'*'</code>s and then adding the new stuff back in.</p>\n"
},
{
"answer_id": 231419,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "<p>Your original code and the proposed solutions so far have a couple of problems in addition to the obvious problem you posted about:</p>\n\n<ul>\n<li>use of invalidated iterators after the string is modified</li>\n<li>dereferencing possibly invalid iterators even before the string is modified (if the string is empty, for example)</li>\n<li>a bug if the expressionBuilder string contains only a single '*' character</li>\n</ul>\n\n<p>Now, the last two items might not really be a problem if the code that uses the snippet/routine is already validating that the string has at least 2 characters, but in case that's not the situation, I believe the following to be more robust in the face of arbitrary values for expressionBuilder:</p>\n\n<pre><code>// using the reverse iterator rbegin() is a nice easy way \n// to get the last character of a string\n\nif ( (expressionBuilder.size() >= 2) &&\n (*expressionBuilder.begin() == '*') &&\n (*expressionBuilder.rbegin() == '*') ) {\n\n expressionBuilder.erase(expressionBuilder.begin());\n\n // can't nicely use rbegin() here because erase() wont take a reverse\n // iterator, and converting reverse iterators to regular iterators\n // results in rather ugly, non-intuitive code\n expressionBuilder.erase(expressionBuilder.end() - 1); // note - not invalid since we're getting it anew\n\n expressionBuilder = \"\\\\b\\\\w*\" + expressionBuilder + \"\\\\w*\\\\b\";\n}\n</code></pre>\n\n<p>Note that this code will work when <code>expressionBuilder</code> is <code>\"\"</code>, <code>\"*\"</code>, or <code>\"**\"</code> in that it does not perform any undefined actions. However, it might not produce the results you want in those cases (that's because I don't know exactly what you do want in those cases). Modify to suit your needs.</p>\n"
},
{
"answer_id": 232383,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 0,
"selected": false,
"text": "<p>Minus the error handling, you could probably just do it like this:</p>\n\n<pre><code>#include <iostream>\n#include <string>\nusing namespace std;\n\nstring stripStar(const string& s) {\n return string(s.begin() + 1, s.end() - 1);\n}\n\nint main() {\n cout << stripStar(\"*word*\") << \"\\n\";\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1544/"
] |
I'm trying to change user input in wildcard form `("*word*")` to a regular expression format. To that end, I'm using the code below to strip off the `'*'` at the beginning and end of the input so that I can add the regular expression characters on either end:
```
string::iterator iter_begin = expressionBuilder.begin();
string::iterator iter_end = expressionBuilder.end();
iter_end--;
if ((char)*iter_begin == '*' && (char)*iter_end == '*')
{
expressionBuilder.erase(iter_begin);
expressionBuilder.erase(iter_end);
expressionBuilder = "\\b\\w*" + expressionBuilder + "\\w*\\b";
}
```
However, the call to `"expressionBuilder.erase(iter_end)"` does *not* erase the trailing `'*'` from the input string so I wind up with an incorrect regular expression. What am I doing wrong here? `"(char)*iter_end == '*'"` must be true for the code inside the if statment to run (which it does), so why doesn't the same iterator work when passed to erase()?
|
Try erasing them in the opposite order:
```
expressionBuilder.erase(iter_end);
expressionBuilder.erase(iter_begin);
```
After erasing the first \*, iter\_end refers to one character past the end of the string in your example. The [STL documentation](http://www.sgi.com/tech/stl/basic_string.html) indicates that iterators are invalidated by `erase()`, so technically my example is wrong too but I believe it will work in practice.
|
231,158 |
<p>I'm writing an ASP.NET webforms app, and I'm using jQuery for my AJAX calls. This is working well, but on some occasions, the $.getJSON call is causing a full page postback. I am not using the ASP.NET AJAX library anywhere in the app. I can't reproduce the problem on a consistent basis, and am not sure what is causing it. Here is the jQuery code I am using. Anyone run across this before? Is is possible the previous AJAX call might not have completed, and requests are overlapping?</p>
<pre><code>function getActionMismatch(id) {
setPageElementVisibility();
$(".ActionDetailArea").slideUp("fast");
$("#AjaxLoader_Action").show();
$.getJSON("Main.aspx?Callback=GetMismatch",
{ MismatchId: id },
function(result) {
$("#adMismatchId").text(result.MismatchId);
$("#adAuthMerchId").text(result.AuthorizationMerchantId);
$("#adSttlMerchId").text(result.SettlementMerchantId);
$("#adCreateDate").text(formatJSONDate(Date(result.AppendDts)));
$(".ActionDetailArea").slideDown('fast', toggleBlock('...click Adjust Promo to enter details', true));
$("#AjaxLoader_Action").hide();
}
);
return false;
}
</code></pre>
|
[
{
"answer_id": 231275,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>Under some circumstances when jQuery can't do a AJAX call, so it creates a hidden iframe and does a normal submit from there. I'm guessing that some how that process is breaking down.</p>\n"
},
{
"answer_id": 234720,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 3,
"selected": true,
"text": "<p>How are you triggering that JavaScript function? </p>\n\n<p>If it's a client-side click handler on a control like a Button, you need to be sure to call preventDefault(). Otherwise, the browser will submit the form and cause a postback, even while the AJAX callback is in progress.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
I'm writing an ASP.NET webforms app, and I'm using jQuery for my AJAX calls. This is working well, but on some occasions, the $.getJSON call is causing a full page postback. I am not using the ASP.NET AJAX library anywhere in the app. I can't reproduce the problem on a consistent basis, and am not sure what is causing it. Here is the jQuery code I am using. Anyone run across this before? Is is possible the previous AJAX call might not have completed, and requests are overlapping?
```
function getActionMismatch(id) {
setPageElementVisibility();
$(".ActionDetailArea").slideUp("fast");
$("#AjaxLoader_Action").show();
$.getJSON("Main.aspx?Callback=GetMismatch",
{ MismatchId: id },
function(result) {
$("#adMismatchId").text(result.MismatchId);
$("#adAuthMerchId").text(result.AuthorizationMerchantId);
$("#adSttlMerchId").text(result.SettlementMerchantId);
$("#adCreateDate").text(formatJSONDate(Date(result.AppendDts)));
$(".ActionDetailArea").slideDown('fast', toggleBlock('...click Adjust Promo to enter details', true));
$("#AjaxLoader_Action").hide();
}
);
return false;
}
```
|
How are you triggering that JavaScript function?
If it's a client-side click handler on a control like a Button, you need to be sure to call preventDefault(). Otherwise, the browser will submit the form and cause a postback, even while the AJAX callback is in progress.
|
231,159 |
<p>I remember from C days that we were encouraged to use</p>
<pre><code>i > -1
</code></pre>
<p>instead of</p>
<pre><code>i >= 0
</code></pre>
<p>because of performance.</p>
<p>Does this still apply in the C# .NET world? What are the performance implications of using one over the other with today's compilers? i.e. Is the compiler clever enough to optimize these for you?</p>
<p>(As an aside try and type the question "use >= or >" into the question field on Stack Overflow and see what happens.)</p>
|
[
{
"answer_id": 231170,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 3,
"selected": false,
"text": "<p>No you don't need to do this any more. Yes the compilers have become much smarter and the two expressions have no performance differences.</p>\n"
},
{
"answer_id": 231179,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 7,
"selected": true,
"text": "<p>No, there are no performance issues associated with comparison operators. And any good compiler would optimize something this trivial anyway.</p>\n\n<p>I'm not sure where you got the suggestion to use \"i > -1\" rather than \"i >= 0\". On the x86 architecture, it makes no difference which you use: either case takes exactly two instructions... one to compare and one to jump:</p>\n\n<pre><code> ;; if (i > -1) {\n cmp eax, -1\n jle else\nthen:\n ...\nelse:\n\n ;; if (i >= 0) {\n cmp eax, 0\n jl else\nthen:\n ...\nelse:\n</code></pre>\n\n<p>On most RISC architectures that I know, \"i >= 0\" may actually be faster since there is usually a dedicated zero register, and \"i > -1\" may require loading a constant. For example, MIPS only has a < instruction (no <=). Here is how the two constructs would be (naively!) expressed in MIPS assembly language:</p>\n\n<pre><code> // if (i >= 0) { (assuming i is in register %t0)\n\n stl $t1, $0, $t0 // in C: t1 = (0 < t0)\n beq $t1, $0, else // jump if t1 == 0, that is if t0 >= 0\n nop\nthen:\n ...\nelse:\n\n// if (i > -1) { (assuming i is in register %t0)\n\n addi $t2, $0, -1 // in C: t2 = -1\n stl $t1, $t2, $t0 // in C: t1 = (t2 < t0) = (-1 < t0)\n bne $t1, $0, else // jump if t1 != 0, that is if t0 > -1\n nop\nthen:\n ...\nelse:\n</code></pre>\n\n<p>So in the naive, general case, it will actually be one instruction faster to do \"i >= 0\" on MIPS. Of course, RISC code is so heavily optimizable that a compiler would likely change either of these instruction sequences almost beyond recognition :-)</p>\n\n<p>So... the short answer is no no no, no difference.</p>\n"
},
{
"answer_id": 231232,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I remember from C days that we were encouraged to use .... because of performance.</p>\n</blockquote>\n\n<p>Are you <em>sure</em> about that? I've worked with computers going back to the early '70's (yes, at my father's knee...), and I've never seen a CPU that couldn't process >= just as fast as >. (BH \"Branch High\" vs. BNL \"Branch Not Low\" in IBM360 talk).</p>\n"
},
{
"answer_id": 231233,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>There is a very similar question (no criticism implied - as you say, searching for symbols is tricky) here: <a href=\"https://stackoverflow.com/questions/182600/should-one-use-or-in-a-for-loop#182620\">\"Should one use <code><</code> or <code><=</code> in a for loop\"</a></p>\n\n<p>(Yes, I happen to be able to find it easily as I've got a lot of upvotes on my answer...)</p>\n\n<p>Basically, do whatever's most readable. The day someone correctly guesses that making a change away from the most readable form is going to solve a performance problem (without the help of a profiler) is the day I stop talking about performance :)</p>\n"
},
{
"answer_id": 231237,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "<p>Quite apart from the fact that any decent compiler does the right thing, and apart from that fact that in modern architectures there's no speed difference between <code>></code> and <code>>=</code> comparisons, the bigger picture says that this is a \"micro-optimisation\" that doesn't affect runtime performance in the vast majority of cases.</p>\n\n<p>In the case of comparisons it usually doesn't affect readability whichever way you write it, but there are occasions when picking one boundary over the other is clearer: e.g.,</p>\n\n<pre><code>if (length >= str.size())\n</code></pre>\n\n<p>versus</p>\n\n<pre><code>if (length > str.size() - 1)\n</code></pre>\n\n<p>I don't know about you, but I'd pick option 1 any day. :-) In cases that don't appreciably affect performance, such as this, the more readable option should win.</p>\n"
},
{
"answer_id": 231324,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 2,
"selected": false,
"text": "<p>That might have been true for some shady scripting languages that break down a >= into 2 comparisons, but whoever encouraged you to use that for C... well... you should probably try hard to forget everything they ever told you.</p>\n"
},
{
"answer_id": 231499,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 2,
"selected": false,
"text": "<p>This reminds me of the recommendation to use ++i instead of i++ (pre-increment vs. post-increment) because it was <em>supposedly</em> one instruction faster. (I forget where I originally read about this, but it was probably C/C++ Users' Journal or Dr. Dobb's Journal but I can't seem to find a web reference.)</p>\n\n<p>I seriously doubt that > or >= is faster or slower; instead write your code for clarity.</p>\n\n<p>As a side note, I developed a preference for the pre-increment (++i) operator even if the reason is now potentially outdated.</p>\n"
},
{
"answer_id": 37666570,
"author": "Scott Renz",
"author_id": 6432320,
"author_profile": "https://Stackoverflow.com/users/6432320",
"pm_score": -1,
"selected": false,
"text": "<p>For greater than zero, it must make two checks. It checks if the negative bit is off and it checks if the zero bit is off.</p>\n\n<p>For greater than or equal to zero, it only has to check if the negative bit is off, because we don't care if the zero bit is on or off.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
I remember from C days that we were encouraged to use
```
i > -1
```
instead of
```
i >= 0
```
because of performance.
Does this still apply in the C# .NET world? What are the performance implications of using one over the other with today's compilers? i.e. Is the compiler clever enough to optimize these for you?
(As an aside try and type the question "use >= or >" into the question field on Stack Overflow and see what happens.)
|
No, there are no performance issues associated with comparison operators. And any good compiler would optimize something this trivial anyway.
I'm not sure where you got the suggestion to use "i > -1" rather than "i >= 0". On the x86 architecture, it makes no difference which you use: either case takes exactly two instructions... one to compare and one to jump:
```
;; if (i > -1) {
cmp eax, -1
jle else
then:
...
else:
;; if (i >= 0) {
cmp eax, 0
jl else
then:
...
else:
```
On most RISC architectures that I know, "i >= 0" may actually be faster since there is usually a dedicated zero register, and "i > -1" may require loading a constant. For example, MIPS only has a < instruction (no <=). Here is how the two constructs would be (naively!) expressed in MIPS assembly language:
```
// if (i >= 0) { (assuming i is in register %t0)
stl $t1, $0, $t0 // in C: t1 = (0 < t0)
beq $t1, $0, else // jump if t1 == 0, that is if t0 >= 0
nop
then:
...
else:
// if (i > -1) { (assuming i is in register %t0)
addi $t2, $0, -1 // in C: t2 = -1
stl $t1, $t2, $t0 // in C: t1 = (t2 < t0) = (-1 < t0)
bne $t1, $0, else // jump if t1 != 0, that is if t0 > -1
nop
then:
...
else:
```
So in the naive, general case, it will actually be one instruction faster to do "i >= 0" on MIPS. Of course, RISC code is so heavily optimizable that a compiler would likely change either of these instruction sequences almost beyond recognition :-)
So... the short answer is no no no, no difference.
|
231,175 |
<p>Where can I find comprehensive documentation for MOQ? I'm just starting with mocking and am having difficulty getting my head around it. I've read through all the links at <a href="http://code.google.com/p/moq/wiki/QuickStart" rel="noreferrer">http://code.google.com/p/moq/wiki/QuickStart</a> but can't seem to find a tutorial or gentle introduction.</p>
<p>I have also looked briefly at Rhino Mocks but found it very confusing.</p>
<hr>
<p>Yes - I read Stephen Walthers article - very helpful. I also went through the links. I can't seem to watch the video at <strike><a href="http://www.bestechvideos.com/2008/06/08/dimecasts-net-introduction-to-mocking-with-moq" rel="noreferrer">http://www.bestechvideos.com/2008/06/08/dimecasts-net-introduction-to-mocking-with-moq</a></strike> <sup>[broken link]</sup></p>
<p>Specifically I am trying to determine whether an event was raised from the mocked class. I can't get the example for events on the QuickStarts page to compile. On the google groups, Daniel explained that CreateEventHandler can only handle an event of type <code>EventHandler<TEventArgs></code>, but even then I can't get the code to compile.</p>
<p>More specifically I have a class that implements <code>INotifyChanged</code>. </p>
<pre><code>public class Entity : INotifyChanged
{
public event PropertyChangingEventHandler PropertyChanging;
public int Id
{
get {return _id;}
set {
_id = value;
OnPropertyChanged("Id");
}
}
protected void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
etc .....
}
</code></pre>
<p>How do I mock the class to test whether the <code>PropertyChanged</code> event was fired? I can't rewrite the event to <code>public event EventHandler<PropertyChangedEventArgs></code> becuase I get this error:</p>
<blockquote>
<p>Error 1 'CoreServices.Notifier' does not implement interface member System.ComponentModel.INotifyPropertyChanged.PropertyChanged'. 'CoreServices.Notifier.PropertyChanged' cannot implement 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' because it does not have the matching return type of 'System.ComponentModel.PropertyChangedEventHandler'.</p>
</blockquote>
|
[
{
"answer_id": 231194,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "<p>Have you watched <a href=\"http://dimecasts.net/Content/WatchEpisode/8\" rel=\"noreferrer\">Introduction to Mocking with Moq</a>? It's an introductory overview of using Moq and is intended for those who are new to either mocking in general, or the Moq framework itself.</p>\n"
},
{
"answer_id": 231239,
"author": "Brian J Cardiff",
"author_id": 30948,
"author_profile": "https://Stackoverflow.com/users/30948",
"pm_score": 3,
"selected": false,
"text": "<p>Have you read the linked pages at <a href=\"https://github.com/Moq/moq4/wiki/Quickstart\" rel=\"nofollow noreferrer\">https://github.com/Moq/moq4/wiki/Quickstart</a> ?\nfor example <a href=\"http://weblogs.asp.net/stephenwalther/archive/2008/06/11/tdd-introduction-to-moq.aspx\" rel=\"nofollow noreferrer\">this one</a> (probably moved to <a href=\"http://stephenwalther.com/archive/2008/06/12/tdd-introduction-to-moq.aspx\" rel=\"nofollow noreferrer\">stephen walthers personal blog</a>)</p>\n"
},
{
"answer_id": 276358,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 5,
"selected": false,
"text": "<p>Moq's latest documentation is now available at github wiki page:</p>\n\n<p><a href=\"https://github.com/Moq/moq4/wiki/Quickstart\" rel=\"noreferrer\">https://github.com/Moq/moq4/wiki/Quickstart</a></p>\n\n<p>Previously they were on Google Code. As well as the wiki and other online resources, there's full documentation in Windows .CHM help-file format included in the <a href=\"https://github.com/Moq/moq4/wiki/Quickstart\" rel=\"noreferrer\">Moq binary download</a> linked from <a href=\"https://github.com/Moq/\" rel=\"noreferrer\">the Moq homepage</a>.</p>\n"
},
{
"answer_id": 8546583,
"author": "TrueWill",
"author_id": 161457,
"author_profile": "https://Stackoverflow.com/users/161457",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I am trying to determine whether an event was raised from the mocked\n class.</p>\n</blockquote>\n\n<p>Are you? Or are you trying to determine if the <code>Id</code> property was set? Remember, by default a mock has no behavior. It's not raising notification events.</p>\n\n<p>I'd do:</p>\n\n<pre><code>const int ExpectedId = 123;\nmockEntity.VerifySet(x => x.Id = ExpectedId);\n</code></pre>\n\n<p>This assumes that Entity implements an interface; one example:</p>\n\n<pre><code>public interface IKeyedEntity\n{\n int Id { get; set; }\n}\n</code></pre>\n\n<p>That said, if <code>Entity</code> is a <a href=\"http://en.wikipedia.org/wiki/Plain_Old_CLR_Object\" rel=\"nofollow\">POCO</a> with no interesting behavior I would neither implement an interface (other than <code>INotifyChanged</code>) nor mock it. Test with an actual <code>Entity</code> instance (just don't use a database). Reserve mocking for services and complex dependencies.</p>\n\n<p>For more Moq features, see</p>\n\n<p><a href=\"http://blogs.clariusconsulting.net/kzu/old-style-imperative-mocks-vs-moq-functional-specifications/\" rel=\"nofollow\">Old style imperative mocks vs moq functional specifications</a>\nand\n<a href=\"http://groups.google.com/group/moqdisc/browse_thread/thread/7c0477e3f4e6f400?pli=1\" rel=\"nofollow\">Mock.Of - how to specify behavior? (thread)</a>. I also posted my own example of <a href=\"http://www.truewill.net/myblog/index.php/2011/04/20/moq_v4_functional_specifications\" rel=\"nofollow\">Moq v4 functional specifications</a>.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30046/"
] |
Where can I find comprehensive documentation for MOQ? I'm just starting with mocking and am having difficulty getting my head around it. I've read through all the links at <http://code.google.com/p/moq/wiki/QuickStart> but can't seem to find a tutorial or gentle introduction.
I have also looked briefly at Rhino Mocks but found it very confusing.
---
Yes - I read Stephen Walthers article - very helpful. I also went through the links. I can't seem to watch the video at <http://www.bestechvideos.com/2008/06/08/dimecasts-net-introduction-to-mocking-with-moq> [broken link]
Specifically I am trying to determine whether an event was raised from the mocked class. I can't get the example for events on the QuickStarts page to compile. On the google groups, Daniel explained that CreateEventHandler can only handle an event of type `EventHandler<TEventArgs>`, but even then I can't get the code to compile.
More specifically I have a class that implements `INotifyChanged`.
```
public class Entity : INotifyChanged
{
public event PropertyChangingEventHandler PropertyChanging;
public int Id
{
get {return _id;}
set {
_id = value;
OnPropertyChanged("Id");
}
}
protected void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
etc .....
}
```
How do I mock the class to test whether the `PropertyChanged` event was fired? I can't rewrite the event to `public event EventHandler<PropertyChangedEventArgs>` becuase I get this error:
>
> Error 1 'CoreServices.Notifier' does not implement interface member System.ComponentModel.INotifyPropertyChanged.PropertyChanged'. 'CoreServices.Notifier.PropertyChanged' cannot implement 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' because it does not have the matching return type of 'System.ComponentModel.PropertyChangedEventHandler'.
>
>
>
|
Moq's latest documentation is now available at github wiki page:
<https://github.com/Moq/moq4/wiki/Quickstart>
Previously they were on Google Code. As well as the wiki and other online resources, there's full documentation in Windows .CHM help-file format included in the [Moq binary download](https://github.com/Moq/moq4/wiki/Quickstart) linked from [the Moq homepage](https://github.com/Moq/).
|
231,189 |
<p>What tool or method do you recommend to find and replace values in your code? If code is on Linux/Unix, are find and grep the best method?</p>
|
[
{
"answer_id": 231210,
"author": "biozinc",
"author_id": 30698,
"author_profile": "https://Stackoverflow.com/users/30698",
"pm_score": 1,
"selected": false,
"text": "<p>I'm assuming you intend to rename a variable.</p>\n\n<p>It depends on what the body of code is. For C#, Visual Studio's renaming tool is very good. Remember that for it to work reliably, you need the renaming to work hand in hand with the compiler/interpreter, so you can make sure you only make the change in the right scope.</p>\n\n<p>If it is a very simple find/replace, surely the lowly notepad would do an OK job?</p>\n"
},
{
"answer_id": 231213,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 0,
"selected": false,
"text": "<p>find and grep don't build indecies, so they're always going to be slower than alternatives that do. That said, they work fine if your codebase is only a few dozen files.in Fi</p>\n\n<p>Eclipse has a nice file search feature (Ctrl+H). It can also take language semantics into consideration if you have the right plugins (Java works out of the box, of course). The only caveat is that it can be a bit slow the first time you search in a certain file set.</p>\n"
},
{
"answer_id": 231241,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 4,
"selected": true,
"text": "<p>Take a look at <a href=\"http://petdance.com/ack/\" rel=\"nofollow noreferrer\">ack</a>, which is designed for searching big codebases.</p>\n\n<p>For replacing, look at Perl's -i, -p and -e flags. You can do stuff like:</p>\n\n<pre><code>$ perl -i -p -e's/\\bthisword\\b/thatword/g' $(find . -name *.html)\n</code></pre>\n\n<p>to replace all instances of thisword with thatword in all .html files in the tree.</p>\n"
},
{
"answer_id": 231290,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "<p><code>find</code> and <code>grep</code> will find the word you're looking for, but to replace it you need to use <code>sed</code>, <code>awk</code> or your favorite stream editing filter.</p>\n\n<p><code>groovy</code>, <code>python</code>, <code>perl</code> will all do search/replace operations - use your favorite or pick one to learn.</p>\n\n<p>For operations on a code base, I'll use <code>find | sed</code> for simple operations (<code>cygwin</code> is your friend) and the IDE's search/replace with regex support for more complex operations. Eclipse, Idea, Visual Studio and even SQL Server Manglement Studio have powerful search/replace functions. The bad news is that not all of them use the same regex syntax.</p>\n"
},
{
"answer_id": 231348,
"author": "levhita",
"author_id": 7946,
"author_profile": "https://Stackoverflow.com/users/7946",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look into PowerGrep... it has ads everywhere in SO. I'm starting to want it even when i don't really need it-</p>\n\n<p>PD: They have a 15 days free demo, so if this is a small job you could just use the demo.</p>\n"
},
{
"answer_id": 813847,
"author": "Sen",
"author_id": 58480,
"author_profile": "https://Stackoverflow.com/users/58480",
"pm_score": 1,
"selected": false,
"text": "<p>This is just a tip to Andy's above accepted answer.could not add this as a comment due to less reputation</p>\n\n<p>Use ! as a seperator when you have tough time escaping the strings</p>\n\n<p>e.g $ perl -i -p -e's!\\bthisword\\b!thatword!g' $(find . -name *.html)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26180/"
] |
What tool or method do you recommend to find and replace values in your code? If code is on Linux/Unix, are find and grep the best method?
|
Take a look at [ack](http://petdance.com/ack/), which is designed for searching big codebases.
For replacing, look at Perl's -i, -p and -e flags. You can do stuff like:
```
$ perl -i -p -e's/\bthisword\b/thatword/g' $(find . -name *.html)
```
to replace all instances of thisword with thatword in all .html files in the tree.
|
231,191 |
<p>Ok simple question. I have a JSF application, containing a login page. The problem is if the user loads the login page, leaves it for a while, then tries to login the session expires and a ViewExpiredException is thrown. I could redirect back to the login when this happens, but that isn't very smooth. How can I allow this flow to properly login without an additional attempt?</p>
|
[
{
"answer_id": 232829,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Couple of slightly hacky solutions:</p>\n\n<ul>\n<li>(Very hacky) use a <code><meta http-equiv=\"refresh\" content=\"5\"/></code> tag to automatically reload the page every so often.</li>\n<li>Use a JavaScript function to periodically send a 'ping' request to the server to keep the session alive.</li>\n</ul>\n\n<p>We use <a href=\"http://www.icefaces.org\" rel=\"nofollow noreferrer\">IceFaces</a> at work which automatically detects when your session has expired and displays a pop-up alerting you to the fact. But we do still sometimes have problems on the login page for some reason.</p>\n"
},
{
"answer_id": 262771,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like your login page is in session scope, when it really doesn't need to be. Request scope should be fine for a login page (since, realistically there shouldn't be anything in session before the user logs in). Once the user logs in, you may have this issue crop back up, but Phill's ideas are very good from there on.</p>\n"
},
{
"answer_id": 265908,
"author": "Serxipc",
"author_id": 34009,
"author_profile": "https://Stackoverflow.com/users/34009",
"pm_score": 0,
"selected": false,
"text": "<p>With jsp you can disable the session for a page including this directive <code><%@ page session=\"false\" %></code>. There must be something similar for jsf.</p>\n"
},
{
"answer_id": 894798,
"author": "mtpettyp",
"author_id": 98632,
"author_profile": "https://Stackoverflow.com/users/98632",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Update</strong></p>\n\n<p>As of Mojarra 2.1.19 / 2.2.0 you can now set the transient attribute of the <code><f:view></code> to true:</p>\n\n<pre><code><f:view transient=\"true\">\n Your regular content\n</f:view>\n</code></pre>\n\n<p>You can read about in on <a href=\"https://stackoverflow.com/users/157882/balusc\">Balusc's</a> blog here:</p>\n\n<p><a href=\"http://balusc.blogspot.com.br/2013/02/stateless-jsf.html\" rel=\"nofollow noreferrer\">http://balusc.blogspot.com.br/2013/02/stateless-jsf.html</a></p>\n\n<p><strong>Original</strong></p>\n\n<p>If you're using Facelets you can create your own ViewHandler to handle this:</p>\n\n<pre><code>public class LoginViewHandler extends FaceletViewHandler\n{\n public LoginViewHandler( ViewHandler viewHandler )\n {\n super( viewHandler );\n }\n\n @Override\n public UIViewRoot restoreView( FacesContext ctx, String viewId )\n {\n UIViewRoot viewRoot = super.restoreView( ctx, viewId );\n\n if ( viewRoot == null && viewId.equals( \"/login.xhtml\" ) )\n {\n // Work around Facelet issue\n initialize( ctx );\n\n viewRoot = super.createView( ctx, viewId );\n ctx.setViewRoot( viewRoot );\n\n try\n {\n buildView( ctx, viewRoot );\n }\n catch ( IOException e )\n {\n log.log( Level.SEVERE, \"Error building view\", e ); \n }\n }\n\n return viewRoot;\n }\n}\n</code></pre>\n\n<p>Change \"/login.xhtml\" to your login page. This checks to see if it can restore your view, and if it cannot and the current view is your login page it will create and build the view for you.</p>\n\n<p>Set this in your face-config.xml as follows:</p>\n\n<pre><code><application>\n <!-- snip -->\n <view-handler>my.package.LoginViewHandler</view-handler>\n</application>\n</code></pre>\n\n<p>If you're using JSF without Facelets (i.e. JSPs) you can try having the class extend ViewHandlerWrapper - note that buildView() will not be available. Hopefully createView() on it's own will set the view up correctly but I'm not 100% sure with JSF/JSP.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17614/"
] |
Ok simple question. I have a JSF application, containing a login page. The problem is if the user loads the login page, leaves it for a while, then tries to login the session expires and a ViewExpiredException is thrown. I could redirect back to the login when this happens, but that isn't very smooth. How can I allow this flow to properly login without an additional attempt?
|
**Update**
As of Mojarra 2.1.19 / 2.2.0 you can now set the transient attribute of the `<f:view>` to true:
```
<f:view transient="true">
Your regular content
</f:view>
```
You can read about in on [Balusc's](https://stackoverflow.com/users/157882/balusc) blog here:
<http://balusc.blogspot.com.br/2013/02/stateless-jsf.html>
**Original**
If you're using Facelets you can create your own ViewHandler to handle this:
```
public class LoginViewHandler extends FaceletViewHandler
{
public LoginViewHandler( ViewHandler viewHandler )
{
super( viewHandler );
}
@Override
public UIViewRoot restoreView( FacesContext ctx, String viewId )
{
UIViewRoot viewRoot = super.restoreView( ctx, viewId );
if ( viewRoot == null && viewId.equals( "/login.xhtml" ) )
{
// Work around Facelet issue
initialize( ctx );
viewRoot = super.createView( ctx, viewId );
ctx.setViewRoot( viewRoot );
try
{
buildView( ctx, viewRoot );
}
catch ( IOException e )
{
log.log( Level.SEVERE, "Error building view", e );
}
}
return viewRoot;
}
}
```
Change "/login.xhtml" to your login page. This checks to see if it can restore your view, and if it cannot and the current view is your login page it will create and build the view for you.
Set this in your face-config.xml as follows:
```
<application>
<!-- snip -->
<view-handler>my.package.LoginViewHandler</view-handler>
</application>
```
If you're using JSF without Facelets (i.e. JSPs) you can try having the class extend ViewHandlerWrapper - note that buildView() will not be available. Hopefully createView() on it's own will set the view up correctly but I'm not 100% sure with JSF/JSP.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.