qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
210,097
|
<p>I have a table that has an insert trigger on it. If I insert in 6000 records into this table in one insert statement from a stored procedure, will the stored procedure return before the insert trigger completes?</p>
<p>Just to make sure that I'm thinking correctly, the trigger should only be called (i know 'called' isn't the right word) once because there was only 1 insert statement, right?</p>
<p>My main question is: will the sproc finish even if the trigger hasn't completed?</p>
|
[
{
"answer_id": 210113,
"author": "tom.dietrich",
"author_id": 15769,
"author_profile": "https://Stackoverflow.com/users/15769",
"pm_score": 6,
"selected": true,
"text": "inserted"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
210,120
|
<p>I have a symlink to an important directory. I want to get rid of that symlink, while keeping the directory behind it. </p>
<p>I tried <code>rm</code> and get back <code>rm: cannot remove 'foo'</code>.<br>
I tried <code>rmdir</code> and got back <code>rmdir: failed to remove 'foo': Directory not empty</code><br>
I then progressed through <code>rm -f</code>, <code>rm -rf</code> and <code>sudo rm -rf</code></p>
<p>Then I went to find my back-ups.</p>
<p>Is there a way to get rid of the symlink with out throwing away the baby with the bathwater? </p>
|
[
{
"answer_id": 210130,
"author": "Joe Phillips",
"author_id": 20471,
"author_profile": "https://Stackoverflow.com/users/20471",
"pm_score": 10,
"selected": false,
"text": "$ unlink mySymLink\n"
},
{
"answer_id": 210133,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 11,
"selected": true,
"text": "# this works:\nrm foo\n# versus this, which doesn't:\nrm foo/\n rm rmdir"
},
{
"answer_id": 210138,
"author": "TJ L",
"author_id": 12605,
"author_profile": "https://Stackoverflow.com/users/12605",
"pm_score": 3,
"selected": false,
"text": "ln -s /mnt/bar ~/foo rm foo foo foo bar"
},
{
"answer_id": 210143,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 4,
"selected": false,
"text": "skrall@skrall-desktop:~$ mkdir bar\nskrall@skrall-desktop:~$ ln -s bar foo\nskrall@skrall-desktop:~$ ls -l foo\nlrwxrwxrwx 1 skrall skrall 3 2008-10-16 16:22 foo -> bar\nskrall@skrall-desktop:~$ rm foo\nskrall@skrall-desktop:~$ ls -l foo\nls: cannot access foo: No such file or directory\nskrall@skrall-desktop:~$ ls -l bar\ntotal 0\nskrall@skrall-desktop:~$ \n"
},
{
"answer_id": 210524,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 4,
"selected": false,
"text": "$ rm -d symlink\n"
},
{
"answer_id": 12063134,
"author": "DeeEss09",
"author_id": 1615349,
"author_profile": "https://Stackoverflow.com/users/1615349",
"pm_score": 4,
"selected": false,
"text": "rm symlinkname rm symlinkname/ y"
},
{
"answer_id": 25898704,
"author": "Yuri",
"author_id": 4051829,
"author_profile": "https://Stackoverflow.com/users/4051829",
"pm_score": 2,
"selected": false,
"text": "rm linkname"
},
{
"answer_id": 64668932,
"author": "rubel Mazumder",
"author_id": 9214369,
"author_profile": "https://Stackoverflow.com/users/9214369",
"pm_score": 3,
"selected": false,
"text": "unlink <absolute path> unlink ~/<USER>/<SOME OTHER DIRECTORY>/foo"
},
{
"answer_id": 74015472,
"author": "sharmin sultana",
"author_id": 20204999,
"author_profile": "https://Stackoverflow.com/users/20204999",
"pm_score": 0,
"selected": false,
"text": "rm"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8508/"
] |
210,122
|
<p>I recently downloaded the source tarball for a GTK application that I'd like to improve. It uses the standard <code>./configure</code> and <code>make</code> build sequence.</p>
<p>The first time through, <code>configure</code> reported a bunch of unmet build dependencies, such as <code>libgnomeui-2.0</code>. As I usually do, I had to manually go through and find the Debian <code>*-dev</code> package names corresponding to these dependencies... of course the names never match up quite the same, so it gets to be a real hassle.</p>
<p>So what occurred to me is... <strong>are there any helper tools to automatically install the build dependencies listed by the <code>automake</code>/<code>autoconf</code> configuration files???</strong></p>
<p>(I already know about the <code>dpkg-buildpackage</code> tools, but in this case I am interested in building from a raw distribution-independent source tarball, <strong>not</strong> from the Debian package source.)</p>
|
[
{
"answer_id": 210126,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "apt-get build-dep <package>"
},
{
"answer_id": 210192,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 5,
"selected": true,
"text": "auto-apt"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20789/"
] |
210,145
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/144833/most-useful-attributes-in-c">Most Useful Attributes in C#</a> </p>
</blockquote>
<p>besides:</p>
<pre><code>[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{get; set;}
</code></pre>
<p>What other C# Attributes are useful for Properties, after learning these I feel like I'm Missing out.</p>
<p><strong>Related Questions</strong></p>
<p><a href="https://stackoverflow.com/questions/144833/most-useful-attributes-in-c#144929">Most Useful Attributes in C#</a></p>
|
[
{
"answer_id": 210154,
"author": "Greg D",
"author_id": 6932,
"author_profile": "https://Stackoverflow.com/users/6932",
"pm_score": 2,
"selected": false,
"text": "[Browsable]\n"
},
{
"answer_id": 210160,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": false,
"text": "[Obsolete(\"This is an obsolete property\")]\n"
},
{
"answer_id": 210346,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 1,
"selected": false,
"text": "Description Category System.Windows.Forms [AttributeUsage(AttributeTargets.All)]\ninternal sealed class SRDescriptionAttribute : DescriptionAttribute\n{\n private bool replaced;\n\n public SRDescriptionAttribute(string description) : base(description)\n {\n }\n\n public override string Description\n {\n get\n {\n if (!this.replaced)\n {\n this.replaced = true;\n base.DescriptionValue = SR.GetString(base.Description);\n }\n return base.Description;\n }\n }\n}\n\n[AttributeUsage(AttributeTargets.All)]\ninternal sealed class SRCategoryAttribute : CategoryAttribute\n{\n public SRCategoryAttribute(string category) : base(category)\n {\n }\n\n protected override string GetLocalizedString(string value)\n {\n return SR.GetString(value);\n }\n}\n SR ResourceManager"
},
{
"answer_id": 210420,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "[MethodImpl]\n [TypeDescriptor], [DisplayName], [Editor]\n [Serializable], [DataMember], [XmlElement], [XmlAttribute], [NonSerialized], etc\n [PrincipalPermission]\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28717/"
] |
210,169
|
<p>What would be the best way to port an existing Drupal site to a Django application?
I have around 500 pages (mostly books module) and around 50 blog posts. I'm not using any 3rd party modules.
I would like to keep the current URLS (for SEO purposes) and migrate database to Django. I will create a simple blog application, so migrating blog posts should be ok. What would be the best way to serve 500+ pages with Django? I would like to use Admin to edit/add new pages.</p>
|
[
{
"answer_id": 214984,
"author": "akaihola",
"author_id": 15770,
"author_profile": "https://Stackoverflow.com/users/15770",
"pm_score": 2,
"selected": false,
"text": "manage.py inspectdb"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,171
|
<p>I guess the real question is: </p>
<p>If I don't care about dirty reads, will adding the <strong>with (NOLOCK)</strong> hint to a SELECT statement affect the performance of:</p>
<ol>
<li>the current SELECT statement </li>
<li>other transactions against the given table</li>
</ol>
<p>Example:</p>
<pre><code>Select *
from aTable with (NOLOCK)
</code></pre>
|
[
{
"answer_id": 210227,
"author": "tom.dietrich",
"author_id": 15769,
"author_profile": "https://Stackoverflow.com/users/15769",
"pm_score": 9,
"selected": true,
"text": "NOLOCK NOLOCK NOLOCK NOLOCK NOLOCK NOLOCK"
},
{
"answer_id": 35228402,
"author": "WonderWorker",
"author_id": 1271898,
"author_profile": "https://Stackoverflow.com/users/1271898",
"pm_score": 2,
"selected": false,
"text": "WITH (NOLOCK)"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12424/"
] |
210,178
|
<p>Given the Below Tables. How do I get the Distinct name given the other ID of 76 in LINQ?</p>
<pre><code>**Table S**
SID OtherID
------------------------------
1 77
2 76
**Table Q**
QID SID HighLevelNAme LoweLevelName
---------------------------------------
10 1 Name1 Engine
11 1 Name1 SparkPlus
12 1 Name2 Seat
13 1 Name2 Belt
14 1 Name1 Oil
</code></pre>
<p>I want to return a list of </p>
<p>Name1
Name2</p>
<p>The SQL to do this is </p>
<pre><code>SELECT DISTINCT
Q.HighLevelNAme
FROM S
JOIN Q ON Q.SID = S.SID
WHERE
S.OtherID = 76
</code></pre>
<p>I also have Objects that represents each table.</p>
<p>An answer in VB or C# is acceptable.</p>
|
[
{
"answer_id": 210217,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 4,
"selected": true,
"text": "var results = (from QItem in dataContext.QItems\n where QItem.SItem.OtherID == 76\n select QItem.HighLevelName).Distinct();\n"
},
{
"answer_id": 210322,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "List<string> highLevelNames = dataContext\n .Q\n .Where<Q>(item => item.S.OtherID == id)\n .Select<Q, string>(item => item.HighLevelNAme)\n .Distinct()\n .ToList<string>();\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
210,180
|
<p>I've noticed for quite a long time that strange domains such like jsev.com, cssxx.com appered in my firefox status bar from time to time, I always wonder why so many web pages contains resources from these strange domains. I googled it, but found nothing. I guess it's some kind of virus which infect the servers and insert the code. Here is a sample taken from page header of <a href="http://www.eflorenzano.com/threadexample/blog/" rel="nofollow noreferrer">http://www.eflorenzano.com/threadexample/blog/</a>:</p>
<pre><code><script language="javascript" src="http://i.jsev.com./base.2032621946.js"> </script>
<body onmousemove="return fz3824();">
<LINK REL="stylesheet" TYPE="text/css" HREF="http://i.cssxx.com./base2032621947.css">
<A HREF = "http://i.html.com./base2032621947.html"></A>
<SCRIPT LANGUAGE="JAVASCRIPT" SRC="http://i.js.com./base2032621947.js"></SCRIPT>
<SCRIPT LANGUAGE="JAVASCRIPT">
function getuseragnt()
{ var agt = navigator.userAgent.toLowerCase();
agt = agt.replace(/ /g, "");
return agt;
}
document.write("<LINK REL='stylesheet' TYPE='text/css' HREF='http://i.css2js.com./base.css" + getuseragnt() + "_2032621947'>")
</SCRIPT>
</code></pre>
<p>edit: I am on a debian box, only on firefox I see this code, I just tried opera, this code doesn't appear in opera, really strange, never heard of firefox having such problems.</p>
|
[
{
"answer_id": 210212,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<head><title>Tutorial 2</title>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.4.1/build/reset/reset-min.css\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://media.eflorenzano.com/css/example2.css\">\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/jquery-1.2.2.min.js\"></script>\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/jquery.form.js\"></script>\n\n<script type=\"text/javascript\">\n var _POSTER = '';\n var _FORM = '<textarea id=\"id_comment\" rows=\"10\" cols=\"40\" name=\"comment\"></textarea>';\n var _FORM_URL = '/threadexample/threadedcomments/comment/9/1/json/';\n var _REGISTER_URL = '/threadexample/register';\n var _CHECK_EXISTS_URL = '/threadexample/check_exists';\n var _LOGIN_URL = '/threadexample/login';\n var _IS_FOCUSED = null;\n var _ARROW_IMG_BASE = 'http://media.eflorenzano.com/img/arrow_';\n var _VOTE_BASE = '/threadexample/vote/';\n</script>\n\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/example2.js\"></script>\n</head>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925263/"
] |
210,201
|
<p>Can somebody remember what was the command to create an empty file in MSDOS using BAT file?</p>
|
[
{
"answer_id": 210209,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 9,
"selected": true,
"text": "echo. 2>EmptyFile.txt\n"
},
{
"answer_id": 211045,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 9,
"selected": false,
"text": "NUL /dev/null CON /y copy NUL"
},
{
"answer_id": 295214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "type NUL > EmptyFile.txt\n NUL ECHO OutputLineFromLoop >> Emptyfile.txt"
},
{
"answer_id": 1330484,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "TYPE COPY TYPE File1.txt>File2.txt\n File1.txt"
},
{
"answer_id": 5507221,
"author": "Emm",
"author_id": 686634,
"author_profile": "https://Stackoverflow.com/users/686634",
"pm_score": 3,
"selected": false,
"text": "fsutil file createnew file.cmd 0\n"
},
{
"answer_id": 9458324,
"author": "script'n'code",
"author_id": 1234518,
"author_profile": "https://Stackoverflow.com/users/1234518",
"pm_score": 3,
"selected": false,
"text": "ATTRIB -R filename.ext\nCD .>filename.ext\n CD .>filename.ext\n ATTRIB -R filename.ext>NUL\n(CD .>filename.ext)2>NUL\n"
},
{
"answer_id": 22312518,
"author": "Batchman",
"author_id": 3403791,
"author_profile": "https://Stackoverflow.com/users/3403791",
"pm_score": -1,
"selected": false,
"text": "echo. > Filename.txt"
},
{
"answer_id": 23158286,
"author": "n611x007",
"author_id": 611007,
"author_profile": "https://Stackoverflow.com/users/611007",
"pm_score": 6,
"selected": false,
"text": "type nul >EmptyFile.txt\n REM. >EmptyFile.txt\n echo. 2>EmptyFile.txt\n fsutil file createnew EmptyFile.txt 0\n ATTRIB -R filename.ext>NUL\n(CD.>filename.ext)2>NUL\n 0x0D 0x0A \\r\\n echo.>AlmostEmptyFile.txt\n echo . > TheInvisibleFeature <nul >EmptyFile.txt\n %RANDOM%-%TIME:~6,5% <nul >EmptyFile.txt\n *>EmptyFile.txt\n break > file.txt\n"
},
{
"answer_id": 24822936,
"author": "foxidrive",
"author_id": 2299431,
"author_profile": "https://Stackoverflow.com/users/2299431",
"pm_score": 3,
"selected": false,
"text": "break>file.txt\nbreak>\"file with spaces in name.txt\"\n"
},
{
"answer_id": 25181856,
"author": "PeterE",
"author_id": 3918245,
"author_profile": "https://Stackoverflow.com/users/3918245",
"pm_score": 1,
"selected": false,
"text": "SET byte set x=x > EmptyFile.txt\n set PROMPT=%PROMPT% > EmptyFile.txt\n set \"PROMPT=%PROMPT%\" > EmptyFile.txt\n"
},
{
"answer_id": 59906894,
"author": "Wolfpack'08",
"author_id": 445651,
"author_profile": "https://Stackoverflow.com/users/445651",
"pm_score": -1,
"selected": false,
"text": "Set-Content \"your_ignore_file.txt\" .gitignore -Encoding utf8"
},
{
"answer_id": 60583593,
"author": "HaxAddict1337",
"author_id": 12861751,
"author_profile": "https://Stackoverflow.com/users/12861751",
"pm_score": 2,
"selected": false,
"text": "break\ncls\ncolor\ngoto\npushd\npopd\nprompt\ntitle\n CD.\nREM.\n@echo off\ncmd /c\nSTART >FILE\n print print /d:EMPTY_TEXT_FILE nul\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446104/"
] |
210,206
|
<p>I have this regex I built and tested in regex buddy.</p>
<pre><code>"_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}"
</code></pre>
<p>When I use this in .Net C# </p>
<p>I receive the exception</p>
<pre><code>"parsing \"_ [ 0-9]{10}+ +[ 0-9]{10}+ +[ 0-9]{6}+ [ 0-9]{2}\" - Nested quantifier +."
</code></pre>
<p>What does this error mean? Apparently .net doesn't like the expression.</p>
<p>Here is the regex buddy so u can understand my intention with the regex...</p>
<pre><code>_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}
Match the characters "_ " literally «_ »
Match a single character present in the list below «[ 0-9]{10}+»
Exactly 10 times «{10}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {1}+»
Exactly 1 times «{1}+»
Match a single character present in the list below «[ 0-9]{10}+»
Exactly 10 times «{10}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {2}+»
Exactly 2 times «{2}+»
Match a single character present in the list below «[ 0-9]{6}+»
Exactly 6 times «{6}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {2}»
Exactly 2 times «{2}»
Match a single character present in the list below «[ 0-9]{2}»
Exactly 2 times «{2}»
The character " " « »
A character in the range between "0" and "9" «0-9»
</code></pre>
<p>In short...</p>
<p>What is a Nested quantifier?</p>
|
[
{
"answer_id": 210243,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 5,
"selected": true,
"text": "+ {n} {n} + + \"_ [ 0-9]{10} {1}[ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}\"\n"
},
{
"answer_id": 210265,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "(_ [ 0-9]{10})+(\\s{1})+([ 0-9]{10})+(\\s{2})+([ 0-9]{6})+\\s{2}[ 0-9]{2}"
},
{
"answer_id": 210286,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 4,
"selected": false,
"text": "{10}+\n \"_ [ 0-9]{10} [ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}\"\n (?>[0-9]*) [0-9]*+"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
] |
210,225
|
<p>I made a simple game for the iPhone using OpenGL ES. Everything works fine except for this problem:</p>
<p>I turn the phone completely off, then back on, then launch my app and I get this wierd flickering! Every other frame is correct... the incorrect frames are just the same frame over and over again. If I quit the app, launch it again everything is fine. If I quit and restart 10 times in a row everything is fine every time.</p>
<p>But if I turn the phone off, then back on, then launch the app I get the same flickering the first time I launch the app.</p>
<p>Why is this happening?!</p>
<p>Has anyone else had this problem?</p>
<p>Cheers!</p>
|
[
{
"answer_id": 2808695,
"author": "gulchrider",
"author_id": 289447,
"author_profile": "https://Stackoverflow.com/users/289447",
"pm_score": 1,
"selected": false,
"text": "- (void) draw\n{\n [EAGLContext setCurrentContext:context]; \n glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer);\n glViewport(0, 0, backingWidth, backingHeight);\n\n //Render the GLScene...\n [scene draw];\n\n glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer);\n [context presentRenderbuffer:GL_RENDERBUFFER_OES]; \n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
] |
210,233
|
<p>I imagine there are many of you out there who have developed an application online which automates a lot of processes and saves people at your company time and money.</p>
<p>The question is, what are your experiences with developing that application, having it all set in place, then "spicing" it up with some Ajax, so it makes for a better user experience?</p>
<p>Also, what libraries would you suggest using when adding Ajax to an already-developed web application?</p>
<p>Lastly, what are some common processes you see in web applications that Ajax does well with? For example, auto-populating the search box as you type.</p>
|
[
{
"answer_id": 210242,
"author": "IAmCodeMonkey",
"author_id": 27613,
"author_profile": "https://Stackoverflow.com/users/27613",
"pm_score": 0,
"selected": false,
"text": "<asp:ScriptManager\n <asp:UpdatePanel\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
210,250
|
<p>I have an ASP.NET website and when I press F5 it automatically attaches to the ASP.NET Development Server, how do I attach to IIS worker process instead when I press F5?</p>
|
[
{
"answer_id": 8438502,
"author": "yoel halb",
"author_id": 640195,
"author_profile": "https://Stackoverflow.com/users/640195",
"pm_score": 4,
"selected": false,
"text": "c:\\%systemroot%\\system32\\inetsrv\\appcmd list wp\n c:\\%systemroot%\\system32\\cscript iisapp.vbs\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100768/"
] |
210,256
|
<p>I have an XML document, and contained within one of the nodes, I have <code><li></code> tags. I don't need <code><ul></ul></code> tags for Flash because it only accepts <code><li></code> tags anyway. For example, here's part of the XML doc:</p>
<pre><code><node>
<li>item1</li>
<li>item2</li>
</node>
</code></pre>
<p>I want to put all the data within the <code><node></code> tags, <em>with bullets</em>, into a TextArea component in Flash 8.
Note that my textArea is set to accept HTML, and that</p>
<pre><code>textArea.text = "<li>This is bulleted text</li>";
</code></pre>
<p>works just fine. However, the <code><li></code> tags within the XML document are being interpreted as a completely different node, which I obviously do not want. </p>
<p>I tried using a CDATA tag within the XML, and it inputted everything between the <code><node></code> tags, <em>including</em> the <code><li></code> tags with all their brackets. It does that because <code><li></code>'s brackets are being interpreted with the equivalent "& lt;" and "& gt;" for the left/right brackets.</p>
<p>So now I'm stuck with an unordered list in my XML file that I can't read into Flash. Unless, of course, somebody here can help me out?</p>
|
[
{
"answer_id": 8438502,
"author": "yoel halb",
"author_id": 640195,
"author_profile": "https://Stackoverflow.com/users/640195",
"pm_score": 4,
"selected": false,
"text": "c:\\%systemroot%\\system32\\inetsrv\\appcmd list wp\n c:\\%systemroot%\\system32\\cscript iisapp.vbs\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] |
210,261
|
<p>I'm debugging a Cocoa application that can act as a handler to a custom URL protocol. The application works fine when I click on a link after the application has launched, but something is causing the app to crash if it has not launched at the time the link is clicked.</p>
<p>Is there any way that I can start the app in the debugger and "fool" it into thinking that I had just clicked on a link?</p>
|
[
{
"answer_id": 221172,
"author": "Ken",
"author_id": 17320,
"author_profile": "https://Stackoverflow.com/users/17320",
"pm_score": 2,
"selected": false,
"text": "gdb --wait myAppName\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26628/"
] |
210,266
|
<p>In the Java code I'm working with we have an interface to define our Data Access Objects(DAO). Most of the methods take a parameter of a Data Transfer Object (DTO). The problem occurs when an implementation of the DAO needs to refer to a specific type of DTO. The method then needs to do a (to me completely unnecessary cast of the DTO to SpecificDTO. Not only that but the compiler can't enforce any type of type checking for specific implementations of the DAO which should only take as parameters their specifc types of DTOs.
My question is: how do I fix this in the smallest possible manner?</p>
|
[
{
"answer_id": 210282,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 4,
"selected": false,
"text": "DAO<SpecificDTO> dao = new SpecificDAO();\ndao.save(new SpecificDTO());\netc.\n interface DAO<T extends DTO> {\n void save(T);\n}\n\nclass SpecificDAO implements DAO<SpecificDTO> {\n void save(SpecificDTO) {\n // implementation.\n }\n // etc.\n}\n"
},
{
"answer_id": 212810,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 0,
"selected": false,
"text": "DTO user = userDAO.getById(45);\n\n((UserDTO)user).setEmail(newEmail)\n\nuserDAO.update(user);\n public DeprecatedDAO implements DAO\n{\n public void save(DTO dto)\n {\n logger.warn(\"Use type-specific calls from now on\", new Exception());\n }\n}\n\npublic UserDAO extends DeprecatedDAO\n{\n @Deprecated\n public void save(DTO dto)\n {\n super.save(dto);\n save((UserDTO)dto);\n }\n\n public void save(UserDTO dto)\n {\n // do whatever you do to save the object\n }\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,296
|
<p>I've got a website that has windows authentication enable on it. From a page in the website, the users have the ability to start a service that does some stuff with the database.</p>
<p>It works fine for me to start the service because I'm a local admin on the server. But I just had a user test it and they can't get the service started.</p>
<p>My question is:</p>
<hr>
<p><strong>Does anyone know of a way to get a list of services on a specified computer by name using a different windows account than the one they are currently logged in with?</strong></p>
<hr>
<p>I really don't want to add all the users that need to start the service into a windows group and set them all to a local admin on my IIS server.....</p>
<p>Here's some of the code I've got:</p>
<pre><code>public static ServiceControllerStatus FindService()
{
ServiceControllerStatus status = ServiceControllerStatus.Stopped;
try
{
string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
ServiceController[] services = ServiceController.GetServices(machineName);
string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToLower();
foreach (ServiceController service in services)
{
if (service.ServiceName.ToLower() == serviceName)
{
status = service.Status;
break;
}
}
}
catch(Exception ex)
{
status = ServiceControllerStatus.Stopped;
SaveError(ex, "Utilities - FindService()");
}
return status;
}
</code></pre>
<p>My exception comes from the second line in the try block. Here's the error:</p>
<blockquote>
<p>System.InvalidOperationException:
Cannot open Service Control Manager on
computer 'server.domain.com'. This
operation might require other
privileges. --->
System.ComponentModel.Win32Exception:
Access is denied --- End of inner
exception stack trace --- at
System.ServiceProcess.ServiceController.GetDataBaseHandleWithAccess(String
machineName, Int32
serviceControlManaqerAccess) at
System.ServiceProcess.ServiceController.GetServicesOfType(String
machineName, Int32 serviceType) at
TelemarketingWebSite.Utilities.StartService()</p>
</blockquote>
<p>Thanks for the help/info</p>
|
[
{
"answer_id": 210813,
"author": "Rich",
"author_id": 28442,
"author_profile": "https://Stackoverflow.com/users/28442",
"pm_score": 1,
"selected": false,
"text": " <system.web>\n <identity impersonate=\"true\" userName=\"Username\" password=\"Password\" />\n </system.web\n"
},
{
"answer_id": 211135,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 4,
"selected": true,
"text": "string machineName = ConfigurationManager.AppSettings[\"ServiceMachineName\"];\nstring serviceName = ConfigurationManager.AppSettings[\"ServiceName\"];\nServiceController service = new ServiceController( serviceName, machineName );\nreturn service.Status;\n SC_MANAGER_ENUMERATE_SERVICE SC_MANAGER_CONNECT SERVICE_START SERVICE_STOP GENERIC_READ TRUSTEE_IS_GROUP TRUSTEE_IS_WELL_KNOWN_GROUP #include \"windows.h\"\n#include \"accctrl.h\"\n#include \"aclapi.h\"\n\nint main()\n{\n char serviceName[] = \"my-service-name\";\n char userGroup[] = \"Remote Service Controllers\";\n\n // retrieve the security info\n PACL pDacl = NULL;\n PSECURITY_DESCRIPTOR pDescriptor = NULL;\n GetNamedSecurityInfo( serviceName, SE_SERVICE,\n DACL_SECURITY_INFORMATION, NULL, NULL,\n &pDacl, NULL, &pDescriptor );\n\n // add an entry to allow the users to start and stop the service\n EXPLICIT_ACCESS access;\n ZeroMemory( &access, sizeof(access) );\n access.grfAccessMode = GRANT_ACCESS;\n access.grfAccessPermissions = SERVICE_START | SERVICE_STOP;\n access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;\n access.Trustee.TrusteeType = TRUSTEE_IS_GROUP;\n access.Trustee.ptstrName = userGroup;\n PACL pNewDacl;\n SetEntriesInAcl( 1, &access, pDacl, &pNewDacl );\n\n // write the changes back to the service\n SetNamedSecurityInfo( serviceName, SE_SERVICE,\n DACL_SECURITY_INFORMATION, NULL, NULL,\n pNewDacl, NULL );\n\n LocalFree( pNewDacl );\n LocalFree( pDescriptor );\n}\n SC_MANAGER_ENUMERATE_SERVICE"
},
{
"answer_id": 212673,
"author": "Miles",
"author_id": 21828,
"author_profile": "https://Stackoverflow.com/users/21828",
"pm_score": 2,
"selected": false,
"text": "public static ServiceControllerStatus FindService()\n {\n ServiceControllerStatus status = ServiceControllerStatus.Stopped;\n try\n {\n string machineName = ConfigurationManager.AppSettings[\"ServiceMachineName\"];\n string serviceName = ConfigurationManager.AppSettings[\"ServiceName\"].ToLower();\n\n ImpersonationUtil.Impersonate();\n\n ServiceController service = new ServiceController(serviceName, machineName);\n status = service.Status;\n }\n catch(Exception ex)\n {\n status = ServiceControllerStatus.Stopped;\n SaveError(ex, \"Utilities - FindService()\");\n }\n\n return status;\n }\n public static class ImpersonationUtil\n {\n public static bool Impersonate()\n {\n string logon = ConfigurationManager.AppSettings[\"ImpersonationUserName\"];\n string password = ConfigurationManager.AppSettings[\"ImpersonationPassword\"];\n string domain = ConfigurationManager.AppSettings[\"ImpersonationDomain\"];\n\n IntPtr token = IntPtr.Zero;\n IntPtr tokenDuplicate = IntPtr.Zero;\n WindowsImpersonationContext impersonationContext = null;\n\n if (LogonUser(logon, domain, password, 2, 0, ref token) != 0)\n if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)\n impersonationContext = new WindowsIdentity(tokenDuplicate).Impersonate();\n //\n\n return (impersonationContext != null);\n }\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto)]\n public static extern int LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);\n\n [DllImport(\"advapi32.dll\", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]\n public extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);\n }\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
210,309
|
<p>I am having a problem with FCKeditor reverting html entities entered in the source view back to their original unicode representations.
For example when I enter <code>&euro;</code> into the source view, switch to html and then back to source view, the entity is replaced by an actual € symbol.
The bigger problem, as a result, is that this unicode character is then sent back to the server on submit causing character encoding issues with the underlying database table.
Anyone else come across this?
I have tried many combinations of config settings but all to no avail.</p>
|
[
{
"answer_id": 210360,
"author": "Anne Porosoff",
"author_id": 28701,
"author_profile": "https://Stackoverflow.com/users/28701",
"pm_score": 2,
"selected": false,
"text": "€ €"
},
{
"answer_id": 211521,
"author": "mysomic",
"author_id": 27241,
"author_profile": "https://Stackoverflow.com/users/27241",
"pm_score": 2,
"selected": true,
"text": "FCKConfig.ProcessHTMLEntities=true"
},
{
"answer_id": 8560350,
"author": "Laurynas",
"author_id": 316536,
"author_profile": "https://Stackoverflow.com/users/316536",
"pm_score": 2,
"selected": false,
"text": "config.entities = false;\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27241/"
] |
210,321
|
<p>What is the best method for determining if a users browser has cookies enabled in ASP.NET</p>
|
[
{
"answer_id": 2583101,
"author": "nuwan",
"author_id": 309773,
"author_profile": "https://Stackoverflow.com/users/309773",
"pm_score": -1,
"selected": false,
"text": "function cc()\n{\n /* check for a cookie */\n if (document.cookie == \"\") \n {\n /* if a cookie is not found - alert user -\n change cookieexists field value to false */\n alert(\"COOKIES need to be enabled!\");\n\n /* If the user has Cookies disabled an alert will let him know \n that cookies need to be enabled to log on.*/ \n\n document.Form1.cookieexists.value =\"false\" \n } else {\n /* this sets the value to true and nothing else will happen,\n the user will be able to log on*/\n document.Form1.cookieexists.value =\"true\"\n }\n}\n"
},
{
"answer_id": 4902395,
"author": "Keith",
"author_id": 114547,
"author_profile": "https://Stackoverflow.com/users/114547",
"pm_score": -1,
"selected": false,
"text": "Request.Browser.Cookies"
},
{
"answer_id": 19754380,
"author": "meda",
"author_id": 1880431,
"author_profile": "https://Stackoverflow.com/users/1880431",
"pm_score": 3,
"selected": false,
"text": "private bool cookiesAreEnabled()\n{\nbool cookieEnabled = false;\n\nif(Request.Browser.Cookies)\n{\n //Your Browser supports cookies \n if (Request.QueryString[\"TestingCookie\"] == null)\n {\n //not testing the cookie so create it\n HttpCookie cookie = new HttpCookie(\"CookieTest\",\"\");\n Response.Cookies.Add(cookie);\n\n //redirect to same page because the cookie will be written to the client computer, \n //only upon sending the response back from the server \n Response.Redirect(\"Default.aspx?TestingCookie=1\")\n }\n else\n {\n //let's check if Cookies are enabled\n if(Request.Cookies[\"CookieTest\"] == null)\n {\n //Cookies are disabled\n }\n else\n {\n //Cookies are enabled\n cookieEnabled = true;\n } \n }\n\n}\nelse\n{\n // Your Browser does not support cookies\n}\nreturn cookieEnabled;\n}\n function cookiesAreEnabled()\n{ \n var cookieEnabled = (navigator.cookieEnabled) ? 1 : 0; \n\n if (typeof navigator.cookieEnabled == \"undefined\" && cookieEnabled == 0){ \n document.cookie=\"testcookie\"; \n cookieEnabled = (document.cookie.indexOf(\"testcookie\") != -1) ? 1 : 0; \n } \n\n return cookieEnabled == 1;\n}\n"
},
{
"answer_id": 32486604,
"author": "Cerveser",
"author_id": 562597,
"author_profile": "https://Stackoverflow.com/users/562597",
"pm_score": 1,
"selected": false,
"text": "Private Function IsCookieDisabled() As Boolean\n Dim currentUrl As String = Request.RawUrl\n If Request.Browser.Cookies Then\n 'Your Browser supports cookies \n If Request.QueryString(\"cc\") Is Nothing Then\n 'not testing the cookie so create it\n Dim c As HttpCookie = New HttpCookie(\"SupportCookies\", \"true\")\n Response.Cookies.Add(c)\n If currentUrl.IndexOf(\"?\") > 0 Then\n currentUrl = currentUrl + \"&cc=true\"\n Else\n currentUrl = currentUrl + \"?cc=true\"\n End If\n Response.Redirect(currentUrl)\n Else\n 'let's check if Cookies are enabled\n If Request.Cookies(\"SupportCookies\") Is Nothing Then\n 'Cookies are disabled\n Return True\n Else\n 'Cookies are enabled\n Return False\n End If\n End If\n Else\n Return True\n End If\nEnd Function\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1375/"
] |
210,342
|
<p>I have a html page open on my webbrowser object, I can enter username and password okay, but I'm stuck and don't know how to submit the info. Here is the html code for the username/password submit:</p>
<pre><code><div id="signin">
<h2 class="ir">
<em></em>Sign in</h2>
<form action="/login/" method="post">
<input id="login-url" name="login[url]"
type="hidden" value="/characters/" />
<input id="login-urlError" name="login[urlError]"
type="hidden" value="/account/?error=1" />
<fieldset>
<ul>
<li class="row">
<label for="login-username">
Username <span class="req">*</span>
</label>
<input id="login-username" name="login[username]"
type="text" class="TextBox" value="" />
</li>
<li class="row">
<label for="login-password">
Password <span class="req">*</span>
</label>
<input id="login-password" name="login[password]"
type="password" class="TextBox Password" value="" />
</li>
<li class="but">
<input name="login[submit]" type="image"
class="img" alt="Login &raquo;"
src="/_pub/img/hp/but-login.png" />
</li>
</ul>
</fieldset>
</form>
<p>
<a href="/account/password-reset/">ACCOUNT TROUBLE?</a>
</p>
</div>
</code></pre>
<p>I use the following to enter the username and password:</p>
<pre><code>WebBrowser1.Document.GetElementById("login-username").SetAttribute("Value", Information.txtuser.Text)
WebBrowser1.Document.GetElementById("login-password").SetAttribute("Value", Information.txtpass.Text)
</code></pre>
<p>What should I use to submit the info now? I tried getting the element by name and kept getting index out of range error, index should be -1 or 0, but it was.</p>
<p>Your help would be greatly appriecated!!</p>
|
[
{
"answer_id": 281892,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "\nPublic Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean\n Dim MyDoc As New mshtml.HTMLDocument\n Dim DocElements As mshtml.IHTMLElementCollection = Nothing\n Dim LoginForm As mshtml.HTMLFormElement = Nothing\n\n ASPComplete = 0\n WB.Navigate(VitecLoginURI)\n BrowserLoop()\n\n MyDoc = WB.Document.DomDocument\n DocElements = MyDoc.getElementsByTagName(\"input\")\n For Each i As mshtml.IHTMLElement In DocElements\n\n Select Case i.name\n Case \"seLogin$UserName\"\n i.value = UserID\n Case \"seLogin$Password\"\n i.value = Pass\n Case Else\n Exit Select\n End Select\n\n frmServiceCalls.txtOut.Text &= i.name & \" : \" & i.value & \" : \" & i.type & vbCrLf\n Next i\n\n 'Old Method for Clicking submit\n 'WB.Document.Forms(\"form1\").InvokeMember(\"submit\")\n\n\n 'Better Method to click submit\n LoginForm = MyDoc.forms.item(\"form1\")\n LoginForm.item(\"seLogin$LoginButton\").click()\n ASPComplete = 0\n BrowserLoop()\n\n\n\n MyDoc= WB.Document.DomDocument\n DocElements = MyDoc.getElementsByTagName(\"input\")\n For Each j As mshtml.IHTMLElement In DocElements\n frmServiceCalls.txtOut.Text &= j.name & \" : \" & j.value & \" : \" & j.type & vbCrLf\n\n Next j\n\n frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf\n Return 1\nEnd Function\n"
},
{
"answer_id": 517213,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "WebBrowser1.Document.GetElementById(*element id string*).InvokeMember(\"submit\")"
},
{
"answer_id": 2851138,
"author": "Rafael Pileggi",
"author_id": 343286,
"author_profile": "https://Stackoverflow.com/users/343286",
"pm_score": 2,
"selected": false,
"text": "System.Windows.Forms.WebBrowser www;\n\nvoid VerificarWebSites()\n{\n www = new System.Windows.Forms.WebBrowser();\n www.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_login);\n www.Navigate(new Uri(\"http://www.meusite.com.br\"));\n}\n\nvoid www_DocumentCompleted_login(object sender, WebBrowserDocumentCompletedEventArgs e)\n{ \n www.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_login);\n www.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_logado);\n\n www.Document.Forms[0].All[\"tbx_login\"].SetAttribute(\"value\", \"Gostoso\");\n www.Document.Forms[0].All[\"tbx_senha\"].SetAttribute(\"value\", \"abcdef\");\n www.Document.GetElementById(\"btn_login\").Focus();\n www.Document.GetElementById(\"btn_login\").InvokeMember(\"click\");\n}\n\nvoid www_DocumentCompleted_logado(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n System.IO.StreamWriter sw = new StreamWriter(\"c:\\\\saida_teste.txt\");\n sw.Write(www.DocumentText);\n sw.Close();\n MessageBox.Show(e.Url.AbsolutePath);\n}\n"
},
{
"answer_id": 4658440,
"author": "Nasenbaer",
"author_id": 375368,
"author_profile": "https://Stackoverflow.com/users/375368",
"pm_score": 2,
"selected": false,
"text": "SendKeys(CHR(13)) InvokeMember(\"click\")\n"
},
{
"answer_id": 12543016,
"author": "Kushawaha Bharat",
"author_id": 1673443,
"author_profile": "https://Stackoverflow.com/users/1673443",
"pm_score": 1,
"selected": false,
"text": "<HTML>\n\n<body>\n<div align=\"center\"><img src=\"banner.png\" height=\"80px\" /></div>\n<script type=\"text/javascript\">\n$(document).ready(function(){\n $(\"#login\").validate();\n $(\"#login_container\").css({'position': 'absolute', \n 'top' : (($(window).height()/2) - $(\"#login_container\").height()/2)+'px'});\n $(\"#login_container\").css({'left' : (($(window).width()/2) - $(\"#login_container\").width()/2)+'px'});\n });\n </script>\n <div id=\"login_container\">\n <form name=\"login\" id=\"login\" action=\"?q=login\" method=\"post\">\n <table>\n <tr><td>Username</td><td><input type=\"text\" name=\"name\" class=\"required\"/></td></tr>\n <tr><td>Password</td><td><input type=\"password\" name=\"password\" class=\"required\"/></td></tr>\n <tr><td></td><td><input type=\"submit\" name=\"subimt\" value=\"Login\" /></td></tr>\n </table>\n </form>\n </div>\n</body>\n</html>\n form1 Imports System.IO\nImports System.Windows.Forms\n\n\n\nPublic Class Form1\n\n\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n\n\n WebBrowser1.Navigate(\"http://xyz.com\")\n\n\n\n End Sub\n\n Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted\n WebBrowser1.Document.GetElementById(\"name\").SetAttribute(\"Value\", \"bharatlal\")\n WebBrowser1.Document.GetElementById(\"password\").SetAttribute(\"Value\", \"mahato\")\n WebBrowser1.Document.GetElementById(\"subimt\").Focus()\n WebBrowser1.Document.GetElementById(\"subimt\").InvokeMember(\"click\")\n End Sub\nEnd Class\n"
},
{
"answer_id": 26445921,
"author": "user2941395",
"author_id": 2941395,
"author_profile": "https://Stackoverflow.com/users/2941395",
"pm_score": 0,
"selected": false,
"text": " Private Sub bt_continue_Click(sender As Object, e As EventArgs) Handles bt_continue.Click\n wb_apple.Document.GetElementById(\"phoneNumber\").Focus()\n wb_apple.Document.GetElementById(\"phoneNumber\").InnerText = tb_phonenumber.Text\n wb_apple.Document.GetElementById(\"reservationCode\").Focus()\n wb_apple.Document.GetElementById(\"reservationCode\").InnerText = tb_regcode.Text\n 'SendKeys.Send(\"{Tab}{Tab}{Tab}\")\n 'For Each Element As HtmlElement In wb_apple.Document.GetElementsByTagName(\"a\")\n 'If Element.OuterHtml.Contains(\"iReserve.sms.submitButtonLabel\") Then\n 'Element.InvokeMember(\"click\")\n 'Exit For\n ' End If\n 'Next Element\n wb_apple.Document.GetElementById(\"smsPageForm\").Focus()\n wb_apple.Document.GetElementById(\"smsPageForm\").InvokeMember(\"submit\")\n\nEnd Sub\n"
},
{
"answer_id": 33008097,
"author": "Mohammad Ziya ul haq",
"author_id": 5421644,
"author_profile": "https://Stackoverflow.com/users/5421644",
"pm_score": 0,
"selected": false,
"text": "WebBrowser1.Document.GetElementById(\"place id here\").Focus() SendKeys.Send(\"{ENTER}\")"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,344
|
<p>I just installed the first release candidate of Python 3.0 and got this error after typing:</p>
<pre><code>>>> help('modules foo')
</code></pre>
<pre>[...]
LookupError: unknown encoding: uft-8</pre>
<p>Notice that it says <strong>uft</strong>-8 and not <strong>utf</strong>-8</p>
<p>Is this a py3k specific bug or a misconfiguration on my part? I do not have any other versions of Python installed on this French locale Windows XP SP3 machine.</p>
<p><strong>Edit</strong></p>
<p>A <a href="http://bugs.python.org/issue4135?@ok_message=msg%2074871%20created%3Cbr%3Eissue%204135%20created&@template=item" rel="nofollow noreferrer">bug</a> has been filled by <a href="https://stackoverflow.com/users/22899/alex-coventry">Alex Coventry</a> on October 16th.</p>
|
[
{
"answer_id": 210395,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 0,
"selected": false,
"text": "__future__"
},
{
"answer_id": 210417,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 4,
"selected": true,
"text": "met% pwd\n/home/coventry/src/Python-3.0rc1\nmet% rgrep uft-8 .\n./Lib/test/bad_coding.py:# -*- coding: uft-8 -*-\n./py3k/Lib/test/bad_coding.py:# -*- coding: uft-8 -*-\n help"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] |
210,353
|
<p>I have a class that compares 2 instances of the same objects, and generates a list of their differences. This is done by looping through the key collections and filling a set of other collections with a list of what has changed (this may make more sense after viewing the code below). This works, and generates an object that lets me know what exactly has been added and removed between the "old" object and the "new" one.<br>
My question/concern is this...it is really ugly, with tons of loops and conditions. Is there a better way to store/approach this, without having to rely so heavily on endless groups of hard-coded conditions? </p>
<pre><code> public void DiffSteps()
{
try
{
//Confirm that there are 2 populated objects to compare
if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)
{
//<TODO> Find a good way to compare quickly if the objects are exactly the same...hash?
//Compare the StepDoc collections:
OldDocs = SavedStep.StepDocs;
NewDocs = NewStep.StepDocs;
Collection<StepDoc> docstoDelete = new Collection<StepDoc>();
foreach (StepDoc oldDoc in OldDocs)
{
bool delete = false;
foreach (StepDoc newDoc in NewDocs)
{
if (newDoc.DocId == oldDoc.DocId)
{
delete = true;
}
}
if (delete)
docstoDelete.Add(oldDoc);
}
foreach (StepDoc doc in docstoDelete)
{
OldDocs.Remove(doc);
NewDocs.Remove(doc);
}
//Same loop(s) for StepUsers...omitted for brevity
//This is a collection of users to delete; it is the collection
//of users that has not changed. So, this collection also needs to be checked
//to see if the permisssions (or any other future properties) have changed.
foreach (StepUser user in userstoDelete)
{
//Compare the two
StepUser oldUser = null;
StepUser newUser = null;
foreach(StepUser oldie in OldUsers)
{
if (user.UserId == oldie.UserId)
oldUser = oldie;
}
foreach (StepUser newie in NewUsers)
{
if (user.UserId == newie.UserId)
newUser = newie;
}
if(oldUser != null && newUser != null)
{
if (oldUser.Role != newUser.Role)
UpdatedRoles.Add(newUser.Name, newUser.Role);
}
OldUsers.Remove(user);
NewUsers.Remove(user);
}
}
}
catch(Exception ex)
{
string errorMessage =
String.Format("Error generating diff between Step objects {0} and {1}", NewStep.Id, SavedStep.Id);
log.Error(errorMessage,ex);
throw;
}
}
</code></pre>
<hr>
<p>The targeted framework is 3.5.</p>
|
[
{
"answer_id": 210361,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)\n{\n // Body\n}\n if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)\n{\n return;\n}\n// Body\n var oldDocIds = OldDocs.Select(doc => doc.DocId);\nvar newDocIds = NewDocs.Select(doc => doc.DocId);\nvar deletedIds = oldDocIds.Intersect(newDocIds).ToDictionary(x => x);\nvar deletedDocs = oldDocIds.Where(doc => deletedIds.Contains(doc.DocId));\n foreach (StepUser deleted in usersToDelete)\n{\n // Should use SingleOfDefault here if there should only be one\n // matching entry in each of NewUsers/OldUsers. The\n // code below matches your existing loop.\n StepUser oldUser = OldUsers.LastOrDefault(u => u.UserId == deleted.UserId);\n StepUser newUser = NewUsers.LastOrDefault(u => u.UserId == deleted.UserId);\n\n // Existing code here using oldUser and newUser\n}\n"
},
{
"answer_id": 210370,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 0,
"selected": false,
"text": "DiffResults results = object.CompareTo(object2);\n"
},
{
"answer_id": 210412,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 2,
"selected": false,
"text": " Collection<StepDoc> docstoDelete = new Collection<StepDoc>();\nforeach (StepDoc oldDoc in OldDocs)\n {\n bool delete = false;\n foreach (StepDoc newDoc in NewDocs)\n {\n if (newDoc.DocId == oldDoc.DocId)\n {\n delete = true;\n }\n }\n if (delete) docstoDelete.Add(oldDoc);\n }\n foreach (StepDoc doc in docstoDelete)\n {\n OldDocs.Remove(doc);\n NewDocs.Remove(doc);\n }\n oldDocs.FindAll(newDocs.Contains).ForEach(delegate(StepDoc doc) {\n oldDocs.Remove(doc);\n newDocs.Remove(doc);\n });\n"
},
{
"answer_id": 210434,
"author": "Jeff Kotula",
"author_id": 1382162,
"author_profile": "https://Stackoverflow.com/users/1382162",
"pm_score": 0,
"selected": false,
"text": "MyTraverser t =new Traverser(oldDocs, newDocs);\n\nforeach (object oldOne in t)\n{\n if (oldOne.CompareTo(t.CurrentNewOne) != 0)\n {\n // use RTTI to figure out what to do with the object\n }\n}\n"
},
{
"answer_id": 210511,
"author": "Dave",
"author_id": 28757,
"author_profile": "https://Stackoverflow.com/users/28757",
"pm_score": 1,
"selected": false,
"text": "public delegate void BeforeRemoveMatchCallback<T>(T item1, T item2);\n\npublic static void RemoveMatches<T>(\n IList<T> list1, IList<T> list2, \n BeforeRemoveMatchCallback<T> beforeRemoveCallback) \n where T : IComparable<T>\n{\n // looping backwards lets us safely modify the collection \"in flight\" \n // without requiring a temporary collection (as required by a foreach\n // solution)\n for(int i = list1.Count - 1; i >= 0; i--)\n {\n for(int j = list2.Count - 1; j >= 0; j--)\n {\n if(list1[i].CompareTo(list2[j]) == 0)\n {\n // do any cleanup stuff in this function, like your role assignments\n if(beforeRemoveCallback != null)\n beforeRemoveCallback(list[i], list[j]);\n\n list1.RemoveAt(i);\n list2.RemoveAt(j);\n break;\n }\n }\n }\n} \n BeforeRemoveMatchCallback<StepUsers> callback = \ndelegate(StepUsers oldUser, StepUsers newUser)\n{\n if(oldUser.Role != newUser.Role)\n UpdatedRoles.Add(newUser.Name, newUser.Role);\n};\n"
},
{
"answer_id": 1707368,
"author": "Sahil Vashishat",
"author_id": 207733,
"author_profile": "https://Stackoverflow.com/users/207733",
"pm_score": 0,
"selected": false,
"text": "foreach (TextBox t in col)\n{\n foreach (TextBox d in des) // here des and col are list having textboxes\n {\n // here remove first element then and break it\n RemoveAt(0);\n break;\n }\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18449/"
] |
210,355
|
<p>I changed the folder that my WordPress installation was in.</p>
<p>However, this worked fine, except now all my images are not showing up.</p>
<p>The problem is that each post has the full url of the image in it. (not my doing, this seems to be the default setting)</p>
<p>Is there a tool or a quick fix available for this?</p>
|
[
{
"answer_id": 210362,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "'=\"/'"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2490/"
] |
210,359
|
<p>I have a <code>textbox</code> whose input is being handled by jQuery.</p>
<pre><code>$('input.Search').bind("keyup", updateSearchTextbox);
</code></pre>
<p>When I press <code>Enter</code> in the textbox, I get a postback, which messes everything up. How can I trap that Enter and ignore it?</p>
<p>(Just to preempt one possible suggestion: The textbox has to be an <code><asp:textbox ... /></code> - I can't replace it with an <code><input ... /></code>.)</p>
|
[
{
"answer_id": 210366,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": true,
"text": "<script language=\"JavaScript\">\n\nfunction disableEnterKey(e)\n{\n var key; \n if(window.event)\n key = window.event.keyCode; //IE\n else\n key = e.which; //firefox \n\n return (key != 13);\n}\n\n</script> \n textbox.Attributes.Add(\"OnKeyPress\",\"return disableEnterKey(event)\");\n"
},
{
"answer_id": 210427,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 0,
"selected": false,
"text": "updateSearchTextbox updateSearchTextbox = function(e) {\n /// <summary>\n /// Handles keyup event on search textbox\n /// </summary>\n\n if (e.which == \"13\") {\n // update now\n updateConcessions();\n // Don't post back\n return (false);\n } else {\n delayedUpdateConcessions();\n }\n\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
210,371
|
<p>I've had success with <a href="http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/" rel="nofollow noreferrer">LuaSocket</a>'s TCP facility, but I'm having trouble with its FTP module. I always get a timeout when trying to retrieve a (small) file. I can download the file just fine using Firefox or ftp in passive mode (on Ubuntu Dapper Linux).</p>
<p>I thought it might be that I need LuaSocket to use passive FTP, but then I found that it seems to do that by default. The file I'm trying to retrieve via FTP can be accessed with passive FTP via other programs on my machine, but not via active mode. I found <a href="http://lua-users.org/lists/lua-l/2003-09/msg00217.html" rel="nofollow noreferrer">some talk</a> about "hacking" passive mode support into LuaSocket, and that discussion implies that later versions stopped using passive mode, but my version seems to use passive anyway (I'm using 2.0.1; newest is 2.0.2 and does not appear to have any changes relevant to my use case). I'm a little confused about how that post may relate to my situation, partly because it's very old and LuaSocket's source now bears little resemblance to the code in that discussion).</p>
<p>I've boiled my code down to this:</p>
<pre><code>local ftp = require "socket.ftp"
ftp.TIMEOUT = 10
print(ftp.get("ftp://ftp.us.dell.com/app/dpart.txt"))
</code></pre>
<p>This gives me a timeout. I ran it under <code>strace</code> on Linux (same as <code>ptrace</code> on Solaris). Here's an abridged transcript:</p>
<pre><code>socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
fcntl64(3, F_SETFL, O_RDWR|O_NONBLOCK) = 0
recv(3, "230-Welcome to the Dell FTP site."..., 8192, 0) = 971
send(3, "pasv\r\n", 6, 0) = 6
recv(3, 0x8089a58, 8192, 0) = -1 EAGAIN (Resource temporarily unavailable)
select(4, [3], NULL, NULL, {9, 999934}) = 0 (Timeout)
</code></pre>
<p>There's another site I tried connecting to, but it has a password which I can't post here, but in that case the results were slightly different...I got trace like the above but with <code>select()</code> succeeding at the end, then this:</p>
<pre><code>recv(3, "227 Entering Passive Mode (123,456,789,0,12,34)\r\n", 8192, 0) = 49
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 4
fcntl64(4, F_SETFL, O_RDWR|O_NONBLOCK) = 0
connect(4, {sa_family=AF_INET, sin_port=htons(12345), sin_addr=inet_addr("123.456.789.0")}, 16) = -1 EINPROGRESS (Operation now in progress)
select(5, [4], [4], NULL, {9, 999694}) = 0 (Timeout)
</code></pre>
<p>Compare this to the trace of my "ftp" program in passive mode (which works fine, though note that it does not set the sockets to nonblocking like LuaSocket does):</p>
<pre><code>socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 6
write(5, "PASV\r\n", 6) = 6
read(3, "227 Entering Passive Mode (123,456,789,0,12,34)\r\n", 1024) = 51
connect(6, {sa_family=AF_INET, sin_port=htons(12345), sin_addr=inet_addr("123.456.789.0")}, 16) = 0
</code></pre>
<p>So I've tried LuaSocket against these two different FTP sites with different but similar failures. I also tried it from another machine where active FTP works, and it didn't have any better luck there (presumably because LuaSocket is always using passive mode, from what I can tell by reading the source in <code>socket/ftp.lua</code>).</p>
<p>So can anyone here make the LuaSocket two-liner at the top work? Note that on my machine, active FTP to Dell's site doesn't work (I can connect but as soon as I do <code>ls</code> it disconnects), so if you get LuaSocket to work please also note whether active FTP to Dell's site from another program works on your machine.</p>
|
[
{
"answer_id": 214462,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 3,
"selected": true,
"text": "path/to/your/project/socket/ftp.lua - self.try(self.tp:command(\"user\", user or USER))\n+ self.try(self.tp:command(\"USER\", user or USER))\n- self.try(self.tp:command(\"pass\", password or PASSWORD))\n+ self.try(self.tp:command(\"PASS\", password or PASSWORD))\n- self.try(self.tp:command(\"pasv\"))\n+ self.try(self.tp:command(\"PASV\"))\n- self.try(self.tp:command(\"port\", arg))\n+ self.try(self.tp:command(\"PORT\", arg))\n- local command = sendt.command or \"stor\"\n+ local command = sendt.command or \"STOR\"\n- self.try(self.tp:command(\"cwd\", dir))\n+ self.try(self.tp:command(\"CWD\", dir))\n- self.try(self.tp:command(\"type\", type))\n+ self.try(self.tp:command(\"TYPE\", type))\n- self.try(self.tp:command(\"quit\"))\n+ self.try(self.tp:command(\"QUIT\"))\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4323/"
] |
210,375
|
<p>I have been attempting to write some routines to read RSS and ATOM feeds using the new routines available in System.ServiceModel.Syndication, but unfortunately the Rss20FeedFormatter bombs out on about half the feeds I try with the following exception:</p>
<blockquote>
<pre><code>An error was encountered when parsing a DateTime value in the XML.
</code></pre>
</blockquote>
<p>This seems to occur whenever the RSS feed expresses the publish date in the following format:</p>
<blockquote>
<p>Thu, 16 Oct 08 14:23:26 -0700</p>
</blockquote>
<p>If the feed expresses the publish date as GMT, things go fine:</p>
<blockquote>
<p>Thu, 16 Oct 08 21:23:26 GMT</p>
</blockquote>
<p>If there's some way to work around this with XMLReaderSettings, I have not found it. Can anyone assist?</p>
|
[
{
"answer_id": 2724742,
"author": "CleverPatrick",
"author_id": 22399,
"author_profile": "https://Stackoverflow.com/users/22399",
"pm_score": 5,
"selected": false,
"text": "WebClient client = new WebClient();\nusing (XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(feedUrl)))\n{\n SyndicationFeed feed = SyndicationFeed.Load(reader);\n ....\n //do things with the feed\n ....\n}\n public class SyndicationFeedXmlReader : XmlTextReader\n{\n readonly string[] Rss20DateTimeHints = { \"pubDate\" };\n readonly string[] Atom10DateTimeHints = { \"updated\", \"published\", \"lastBuildDate\" };\n private bool isRss2DateTime = false;\n private bool isAtomDateTime = false;\n\n public SyndicationFeedXmlReader(Stream stream) : base(stream) { }\n\n public override bool IsStartElement(string localname, string ns)\n {\n isRss2DateTime = false;\n isAtomDateTime = false;\n\n if (Rss20DateTimeHints.Contains(localname)) isRss2DateTime = true;\n if (Atom10DateTimeHints.Contains(localname)) isAtomDateTime = true;\n\n return base.IsStartElement(localname, ns);\n }\n\n public override string ReadString()\n {\n string dateVal = base.ReadString();\n\n try\n {\n if (isRss2DateTime)\n {\n MethodInfo objMethod = typeof(Rss20FeedFormatter).GetMethod(\"DateFromString\", BindingFlags.NonPublic | BindingFlags.Static);\n Debug.Assert(objMethod != null);\n objMethod.Invoke(null, new object[] { dateVal, this });\n\n }\n if (isAtomDateTime)\n {\n MethodInfo objMethod = typeof(Atom10FeedFormatter).GetMethod(\"DateFromString\", BindingFlags.NonPublic | BindingFlags.Instance);\n Debug.Assert(objMethod != null);\n objMethod.Invoke(new Atom10FeedFormatter(), new object[] { dateVal, this });\n }\n }\n catch (TargetInvocationException)\n {\n DateTimeFormatInfo dtfi = CultureInfo.CurrentCulture.DateTimeFormat;\n return DateTimeOffset.UtcNow.ToString(dtfi.RFC1123Pattern);\n }\n\n return dateVal;\n\n }\n\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4253/"
] |
210,377
|
<p>What's the best way to get an array of all elements in an html document with a specific CSS class using javascript?</p>
<p>No javascript frameworks like jQuery allowed here right now, and I could loop all the elements and check them manually myself. I'm hoping for something a little more elegant.</p>
|
[
{
"answer_id": 210388,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 0,
"selected": false,
"text": "using document.getElementsByTagName('*') className"
},
{
"answer_id": 210393,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 6,
"selected": true,
"text": "getElementsByClassName()"
},
{
"answer_id": 213020,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "document.getElementById() document.getElementsByTagName() if (!document.getElementsByClassName)\n document.getElementsByClassName = function (className)\n{\n var classes = className.split(\" \");\n var classesToCheck = \"\";\n var returnElements = [];\n var match, node, elements;\n\n if (document.evaluate)\n { \n var xhtmlNamespace = \"http://www.w3.org/1999/xhtml\";\n var namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace:null;\n\n for(var j=0, jl=classes.length; j<jl;j+=1)\n classesToCheck += \"[contains(concat(' ', @class, ' '), ' \" + classes[j] + \" ')]\"; \n\n try\n {\n elements = document.evaluate(\".//*\" + classesToCheck, document, namespaceResolver, 0, null);\n }\n catch(e)\n {\n elements = document.evaluate(\".//*\" + classesToCheck, document, null, 0, null);\n }\n\n while ((match = elements.iterateNext()))\n returnElements.push(match);\n }\n else\n {\n classesToCheck = [];\n elements = (document.all) ? document.all : document.getElementsByTagName(\"*\");\n\n for (var k=0, kl=classes.length; k<kl; k+=1)\n classesToCheck.push(new RegExp(\"(^|\\\\s)\" + classes[k] + \"(\\\\s|$)\"));\n\n for (var l=0, ll=elements.length; l<ll;l+=1)\n {\n node = elements[l];\n match = false;\n for (var m=0, ml=classesToCheck.length; m<ml; m+=1)\n {\n match = classesToCheck[m].test(node.className);\n if (!match) break;\n }\n if (match) returnElements.push(node);\n } \n }\n return returnElements;\n}\n"
},
{
"answer_id": 864584,
"author": "Dmitri Farkov",
"author_id": 103647,
"author_profile": "https://Stackoverflow.com/users/103647",
"pm_score": 3,
"selected": false,
"text": "var getElementsByClassName = function(cls, sc){\n //Init\n var elements, i, results = [], curClass; \n\n //Default scope is document\n sc = sc || document;\n\n //Get all children of the scope node\n elements = sc.getElementsByTagName('*');\n for( i=0; i < elements.length; i++ ){\n curClass = elements[i].getAttribute('class');\n if(curClass != null){\n curClass = curClass.split(\" \");\n for( j=0; j < curClass.length; j++){\n if(curClass[j] === cls){\n results.push( elements[i] );\n break;\n }\n }\n }\n }\n\n return results;\n};\n"
},
{
"answer_id": 4162415,
"author": "d rao",
"author_id": 505435,
"author_profile": "https://Stackoverflow.com/users/505435",
"pm_score": 0,
"selected": false,
"text": "var x = document.getElementById(elementid);\nwhile(x){\ndocument.removechild(x);\nx = document.getElementById(elementid);\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
210,383
|
<p>If I have a VB.Net function that returns an Int32, but uses an unsigned int (UInt32) for calculations, etc. How can I convert a variable "MyUintVar32" with a value of say "3392918397 into a standard Int32 in VB.Net? </p>
<p>In c# if I just do a "return (int)(MyUintVar32);", I get -902048899, not an error.</p>
<p>I've tried several different methods. What is the difference in the way c# handles these conversions versus VB.Net?</p>
|
[
{
"answer_id": 210401,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 2,
"selected": false,
"text": "Dim myUInt32 As UInt32 = 3392918397\nDim myInt32 As Int32 = BitConverter.ToInt32(BitConverter.GetBytes(myUInt32), 0)\n"
},
{
"answer_id": 5516475,
"author": "user687979",
"author_id": 687979,
"author_profile": "https://Stackoverflow.com/users/687979",
"pm_score": 3,
"selected": false,
"text": "Dim myUInt32 As UInt32 = 3392918397 \nDim myInt32 As Int32 = Convert.ToInt32(myUInt32.ToString(\"X\"), 16) \n myUInt32 = Convert.ToUInt32(myInt32.ToString(\"X\"), 16)\n Imports System.Runtime.InteropServices\n\n<StructLayout(LayoutKind.Explicit)> _ \n Public Structure UnionInt32 \n <FieldOffset(0)> _ \n Public IntValue As Int32 \n <FieldOffset(0)> _ \n Public UIntValue As UInt32 \nEnd Structure \n\nDim MyUnionInt32 as UnionInt32 \nMyUnionInt32.UIntValue = 3392918397 \nDim IntVal as Int32 = MyUnionInt32.UIntValue '= -902048899 \n MyUnionInt32.IntValue = -902048000 \nDim UIntVal as UInt32 = MyUnionInt32.UIntValue '= 3392919296 \n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,428
|
<p>Is it possible to somehow mark a <code>System.Array</code> as immutable. When put behind a public-get/private-set they can't be added to, since it requires re-allocation and re-assignment, but a consumer can still set any subscript they wish:</p>
<pre><code>public class Immy
{
public string[] { get; private set; }
}
</code></pre>
<p>I thought the <code>readonly</code> keyword might do the trick, but no such luck.</p>
|
[
{
"answer_id": 210441,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 2,
"selected": false,
"text": "IList<> Array.AsReadOnly()"
},
{
"answer_id": 210444,
"author": "Ray Jezek",
"author_id": 28309,
"author_profile": "https://Stackoverflow.com/users/28309",
"pm_score": 6,
"selected": true,
"text": "ReadOnlyCollection<T> Add()"
},
{
"answer_id": 210491,
"author": "Quantenmechaniker",
"author_id": 28727,
"author_profile": "https://Stackoverflow.com/users/28727",
"pm_score": 5,
"selected": false,
"text": "// bad code\n// could still do Path.InvalidPathChars[0] = 'A';\npublic sealed class Path {\n public static readonly char[] InvalidPathChars = \n { '\\\"', '<', '>', '|' };\n}\n public static ReadOnlyCollection<char> GetInvalidPathChars(){\n return Array.AsReadOnly(InvalidPathChars);\n}\n\npublic static char[] GetInvalidPathChars(){\n return (char[])InvalidPathChars.Clone();\n}\n"
},
{
"answer_id": 211840,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 0,
"selected": false,
"text": "interface IImmutable\n{\n public string ValuableCustomerData { get; }\n}\n\nclass Mutable, IImmutable\n{\n public string ValuableCustomerData { get; set; }\n}\n\npublic class Immy\n{\n private List<Mutable> _mutableList = new List<Mutable>();\n\n public IEnumerable<IImmutable> ImmutableItems\n {\n get { return _mutableList.Cast<IMutable>(); }\n }\n}\n"
},
{
"answer_id": 17852590,
"author": "Zenexer",
"author_id": 1188377,
"author_profile": "https://Stackoverflow.com/users/1188377",
"pm_score": 0,
"selected": false,
"text": "Array.AsReadOnly<T> var mutable = new[]\n{\n 'a', 'A',\n 'b', 'B',\n 'c', 'C',\n};\n\nvar immutable = Array.AsReadOnly(mutable);\n immutable ReadOnlyCollection<char> ReadOnlyCollection<T> IList<T> var immutable = new ReadOnlyCollection<char>(new List<char>(mutable));\n IList IList Array.AsReadOnly<T> ReadOnlyCollection<T> // Note that .NET favors Count over Length; all but traditional arrays use Count:\nfor (var i = 0; i < immutable.Count; i++)\n{\n // this[] { get } is present, as ReadOnlyCollection<T> implements IList<T>:\n var element = immutable[i]; // Works\n\n // this[] { set } has to be present, as it is required by IList<T>, but it\n // will throw a NotSupportedException:\n immutable[i] = element; // Exception!\n}\n\n// ReadOnlyCollection<T> implements IEnumerable<T>, of course:\nforeach (var character in immutable)\n{\n}\n\n// LINQ works fine; idem\nvar lowercase =\n from c in immutable\n where c >= 'a' && c <= 'z'\n select c;\n\n// You can always evaluate IEnumerable<T> implementations to arrays with LINQ:\nvar mutableCopy = immutable.ToArray();\n// mutableCopy is: new[] { 'a', 'A', 'b', 'B', 'c', 'C' }\nvar lowercaseArray = lowercase.ToArray();\n// lowercaseArray is: new[] { 'a', 'b', 'c' }\n"
},
{
"answer_id": 73716571,
"author": "KyleMit",
"author_id": 1366033,
"author_profile": "https://Stackoverflow.com/users/1366033",
"pm_score": 0,
"selected": false,
"text": "ImmutableArray using System.Collections.Immutable;\n\nvar arr1 = new [] {1,2,3}.ToImmutableArray();\nvar arr2 = ImmutableArray.Create(new [] {1,2,3});\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
210,446
|
<p>The client connects to the server using GenuineChannels (we are considering switching to DotNetRemoting). What I mean by find is obtain the IP and port number of a server to connect to.</p>
<p>It seems like a brute-force approach would be try every IP on the network try the active ports (not even sure if that's possible) but there must be a better way.</p>
|
[
{
"answer_id": 210464,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 5,
"selected": true,
"text": "using System.Net;\nusing System.Net.Sockets;\n\n[STAThread]\nstatic void Main(string[] args)\n{\n Socket socket = new Socket(AddressFamily.InterNetwork,\n SocketType.Dgram, ProtocolType.Udp);\n socket.Bind(new IPEndPoint(IPAddress.Any, 8002));\n socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001));\n socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(\"hello\"));\n\n int availableBytes = socket.Available;\n if (availableBytes > 0)\n {\n byte[] buffer = new byte[availableBytes];\n socket.Receive(buffer, 0, availableBytes, SocketFlags.None);\n // buffer has the information on how to connect to the server\n }\n}\n"
},
{
"answer_id": 210520,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 3,
"selected": false,
"text": "MZClient.exe Mono.Zeroconf.dll Mono.Zeroconf.Providers.Bonjour.dll var service = new Mono.Zeroconf.RegisterService {\n Name = \"Use Me for Stuff\",\n RegType = \"_daap._tcp\",\n ReplyDomain = \"local.\",\n Port = 0024200,\n TxtRecord = new Mono.Zeroconf.TxtRecord {\n {\"I have no idea what's going on\", \"true\"}}\n };\nservice.Register();\n\nvar browser = new Mono.Zeroconf.ServiceBrowser();\nbrowser.ServiceAdded +=\n delegate(object o, Mono.Zeroconf.ServiceBrowseEventArgs args) {\n Console.WriteLine(\"Found Service: {0}\", args.Service.Name);\n args.Service.Resolved +=\n delegate(object o, Mono.Zeroconf.ServiceBrowseEventArgs args) {\n var s = args.Service;\n Console.WriteLine(\n \"Resolved Service: {0} - {1}:{2} ({3} TXT record entries)\",\n s.FullName, s.HostEntry.AddressList[0], s.Port, s.TxtRecord.Count);\n };\n args.Service.Resolve();\n };\nbrowser.Browse(\"_daap._tcp\", \"local\");\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23822/"
] |
210,455
|
<p>What's the best way for a common library to know what context - a.k.a. the calling app - it is in? I'm in a very controlled enterprise environment... is there a better way for the library to know what application it is getting called from than reading a setting in the config file? What do you use for this type of thing?</p>
<p><code>//the rest of the story</code><br />
I work on the Intranet team for a Fortune 500 manufacturing company. I have created a common library that all of our new .Net applications will make use of. It queries a common database for information about the application and a bunch of other things that are irrelevant to the question. As you can imagine, the common library needs to know what application is calling it. I could just force every application to set a property on some static class or something, but instead I wanted to make it a little more behind the scenes. Currently it requires the developer to put a setting in the app.config or web.config with a key of ApplicationName and a value of - you guessed it - the application name (which is a unique non changing id for us). It then uses Currently it uses <code>ConfigurationManager.AppSettings["ApplicationName"]</code> to pull this in.</p>
|
[
{
"answer_id": 210550,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 0,
"selected": false,
"text": "public interface IIntranetApp\n{\n string GetApplicationName();\n void SetConnectionString(string connectionString);\n // etc... add methods as necessary\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3226/"
] |
210,460
|
<p>How can polymorphism be described in an easy-to-understand way?</p>
<p>We can find a lot of information about the subject on the Internet and books, like in <em><a href="http://en.wikipedia.org/wiki/Type_polymorphism" rel="noreferrer">Type polymorphism</a></em>. But let's try to make it as simple as we can.</p>
|
[
{
"answer_id": 210472,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 0,
"selected": false,
"text": "interface IJobLoader\n"
},
{
"answer_id": 210482,
"author": "Mark A. Nicolosi",
"author_id": 1103052,
"author_profile": "https://Stackoverflow.com/users/1103052",
"pm_score": 6,
"selected": true,
"text": "class Animal\n{\n abstract string MakeNoise ();\n}\n\nclass Cat : Animal {\n string MakeNoise () {\n return \"Meow\";\n }\n}\n\nclass Dog : Animal {\n string MakeNoise () {\n return \"Bark\";\n }\n}\n\nMain () {\n Animal animal = Zoo.GetAnimal ();\n Console.WriteLine (animal.MakeNoise ());\n}\n"
},
{
"answer_id": 210572,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": false,
"text": "Stream public class Stream\n{\n public int Read(byte[] buffer, int offset, int count)\n {\n if (this.mode == \"file\")\n {\n // behave like a file stream\n }\n else if (this.mode == \"network\")\n {\n // behave like a network stream\n }\n else // etc.\n }\n}\n FileStream NetworkStream public class FileStream : Stream\n{\n public override int Read(byte[] buffer, int offset, int count)\n {\n // behave like a file stream\n }\n}\n\npublic class NetworkStream : Stream\n{\n public override int Read(byte[] buffer, int offset, int count)\n {\n // behave like a network stream\n }\n}\n"
},
{
"answer_id": 210863,
"author": "tsellon",
"author_id": 3575,
"author_profile": "https://Stackoverflow.com/users/3575",
"pm_score": 0,
"selected": false,
"text": "string MyFunc(ClassA anA);\nstring MyFunc(ClassB aB);\n"
},
{
"answer_id": 210876,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 0,
"selected": false,
"text": "foreach (Vehicle v in Game.Vehicles)\n{\n v.Stop();\n}\n"
},
{
"answer_id": 210898,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": " dao = XmlDao.createNewInstance() #obj 1\n dao.save( data )\n\n dao = RdbDao.createNewnewInstance() #obj 2\n dao.save( data )\n"
},
{
"answer_id": 211005,
"author": "JPLemme",
"author_id": 1019,
"author_profile": "https://Stackoverflow.com/users/1019",
"pm_score": 1,
"selected": false,
"text": "class BankAccount {\n void SubtractMonthlyFee\n}\n\nclass CheckingAccount : BankAccount {}\n\nclass SavingsAccount : BankAccount {}\n\nAssessFee(BankAccount acct) {\n // This will work for any class derived from\n // BankAccount; even classes that don't exist yet\n acct.SubtractMonthlyFee\n}\n\nmain() {\n\n CheckingAccount chkAcct;\n SavingsAccount saveAcct;\n\n // both lines will compile, because both accounts\n // derive from \"BankAccount\". If you try to pass in\n // an object that doesn't, it won't compile, EVEN\n // if the object has a \"SubtractMonthlyFee\" method.\n AssessFee(chkAcct);\n AssessFee(saveAcct);\n}\n class DatabaseConnection {\n void ReleaseResources\n}\n\nclass FileHandle {\n void ReleaseResources\n}\n\nFreeMemory(Object obj) {\n // This will work for any class that has a \n // \"ReleaseResources\" method (assuming all\n // classes are ultimately derived from Object.\n obj.ReleaseResources\n}\n\nmain() {\n\n DatabaseConnection dbConn;\n FileHandle fh;\n\n // You can pass in anything at all and it will\n // compile just fine. But if you pass in an\n // object that doesn't have a \"ReleaseResources\"\n // method you'll get a run-time error.\n FreeMemory(dbConn);\n FreeMemory(fh);\n FreeMemory(acct); //FAIL! (but not until run-time)\n}\n"
},
{
"answer_id": 211069,
"author": "massimo",
"author_id": 24489,
"author_profile": "https://Stackoverflow.com/users/24489",
"pm_score": -1,
"selected": false,
"text": " void h() { float x=3.0; printf(\"%f\", x); }\n void k() { int y=5; printf(\"%i\", y); }\n void g(void (*f)()) { f(); }\n g(h); // output 3.0\n g(k); // output 5\n void h(void *a) { float* x=(float*)a; printf(\"%f\",*x); }\n void k(void *a) { int* y=(int*)a; printf(\"%i\",*y); }\n void g(void (*f)(void *a),void *a) { f(a); }\n float x=3.0;\n int y=5;\n g(h,&x); // output x\n g(k,&y); // output y\n class Base { virtual public void call()=0; }\nclass H : public Base { float x; public void call() { printf(\"%f\",x);} } h;\nclass K : public Base { int y; public void call() { printf(\"%i\",y);} } k;\nvoid g(Base &f) { f.call(); };\nh.x=3.0;\nk.y=5;\ng(h); // output h.x\ng(k); // output k.x\n"
},
{
"answer_id": 6367890,
"author": "Tony Delroy",
"author_id": 410767,
"author_profile": "https://Stackoverflow.com/users/410767",
"pm_score": 1,
"selected": false,
"text": "struct class int double"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409636/"
] |
210,470
|
<p>Anyone know a QR decoder that works on mac or that might be online? I just need to decode one single image.</p>
|
[
{
"answer_id": 22144524,
"author": "clt60",
"author_id": 632407,
"author_profile": "https://Stackoverflow.com/users/632407",
"pm_score": 4,
"selected": true,
"text": "Image::DecodeQR ./configure --disable-video --without-python --without-gtk --without-qt ImageMagick zbarimg qrcode_file.png\n"
},
{
"answer_id": 47085827,
"author": "The Matt",
"author_id": 8524178,
"author_profile": "https://Stackoverflow.com/users/8524178",
"pm_score": 6,
"selected": false,
"text": "brew install zbar\n zbarimg qrcode_file.png\n"
},
{
"answer_id": 69495435,
"author": "Frederik Rogalski",
"author_id": 11594092,
"author_profile": "https://Stackoverflow.com/users/11594092",
"pm_score": 2,
"selected": false,
"text": "zbar brew install zbar\n Code install /usr/local/bin/zbarimg QRCode2Clipboard.workflow open_QRCode.workflow"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26004/"
] |
210,475
|
<p>I saw this question asked about C# I would like an answer for PHP. I have some old code that has 4 pages of foreach loops and conditions which just makes it hard to read and follow. How would I make this more OO? I was thinking of using SPL Functions but don't fully understand whats involved yet.</p>
|
[
{
"answer_id": 210505,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 0,
"selected": false,
"text": "array_map array_walk"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25143/"
] |
210,496
|
<p>I continue to get this error:</p>
<pre><code>Object '%s' cannot be renamed because the object participates in enforced dependencies
</code></pre>
<p>I need to find a script that will help me to find all the dependencies that there is with this table. I will need to drop them, rename, then bring them back.</p>
<p>SQL Server 2005</p>
|
[
{
"answer_id": 210512,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 3,
"selected": true,
"text": "sp_msforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"\ngo\nsp_msforeachtable \"ALTER TABLE ? DISABLE TRIGGER all\"\ngo\n sp_msforeachtable\"ALTER TABLE ? CHECK CONSTRAINT all\"\ngo\nsp_msforeachtable \"ALTER TABLE ? ENABLE TRIGGER all\"\ngo\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
] |
210,504
|
<p>I'm creating an alt-tab replacement for Vista but I have some problems listing all active programs.</p>
<p>I'm using EnumWindows to get a list of Windows, but this list is huge. It contains about 400 items when I only have 10 windows open. It seems to be a hwnd for every single control and a lot of other stuff.</p>
<p>So I have to filter this list somehow, but I can't manage to do it exactly as alt-tab does.</p>
<p>This is the code I use to filter the list right now. It works pretty well, but I get some unwanted windows like detached tool-windows in Visual Studio and I also miss windows like iTunes and Warcraft3.</p>
<pre><code>private bool ShouldWindowBeDisplayed(IntPtr window)
{
uint windowStyles = Win32.GetWindowLong(window, GWL.GWL_STYLE);
if (((uint)WindowStyles.WS_VISIBLE & windowStyles) != (uint)WindowStyles.WS_VISIBLE ||
((uint)WindowExStyles.WS_EX_APPWINDOW & windowStyles) != (uint)WindowExStyles.WS_EX_APPWINDOW)
{
return true;
}
return false;
}
</code></pre>
|
[
{
"answer_id": 210519,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "BOOL IsAltTabWindow(HWND hwnd)\n{\n // Start at the root owner\n HWND hwndWalk = GetAncestor(hwnd, GA_ROOTOWNER);\n\n // See if we are the last active visible popup\n HWND hwndTry;\n while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry) {\n if (IsWindowVisible(hwndTry)) break;\n hwndWalk = hwndTry;\n }\n return hwndWalk == hwnd;\n}\n"
},
{
"answer_id": 214213,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": " private static bool KeepWindowHandleInAltTabList(IntPtr window)\n {\n if (window == Win32.GetShellWindow()) //Desktop\n return false;\n\n //http://stackoverflow.com/questions/210504/enumerate-windows-like-alt-tab-does\n //http://blogs.msdn.com/oldnewthing/archive/2007/10/08/5351207.aspx\n //1. For each visible window, walk up its owner chain until you find the root owner. \n //2. Then walk back down the visible last active popup chain until you find a visible window.\n //3. If you're back to where you're started, (look for exceptions) then put the window in the Alt+Tab list.\n IntPtr root = Win32.GetAncestor(window, Win32.GaFlags.GA_ROOTOWNER);\n\n if (GetLastVisibleActivePopUpOfWindow(root) == window)\n {\n WindowInformation wi = new WindowInformation(window);\n\n if (wi.className == \"Shell_TrayWnd\" || //Windows taskbar\n wi.className == \"DV2ControlHost\" || //Windows startmenu, if open\n (wi.className == \"Button\" && wi.windowText == \"Start\") || //Windows startmenu-button.\n wi.className == \"MsgrIMEWindowClass\" || //Live messenger's notifybox i think\n wi.className == \"SysShadow\" || //Live messenger's shadow-hack\n wi.className.StartsWith(\"WMP9MediaBarFlyout\")) //WMP's \"now playing\" taskbar-toolbar\n return false;\n\n return true;\n }\n return false;\n }\n\n private static IntPtr GetLastVisibleActivePopUpOfWindow(IntPtr window)\n {\n IntPtr lastPopUp = Win32.GetLastActivePopup(window);\n if (Win32.IsWindowVisible(lastPopUp))\n return lastPopUp;\n else if (lastPopUp == window)\n return IntPtr.Zero;\n else\n return GetLastVisibleActivePopUpOfWindow(lastPopUp);\n }\n"
},
{
"answer_id": 57503105,
"author": "vhanla",
"author_id": 537347,
"author_profile": "https://Stackoverflow.com/users/537347",
"pm_score": 0,
"selected": false,
"text": "\nEnumWindows(@ListApps, 0);\n\nfunction ListApps(LHWindow: HWND; lParam: Pointer): Boolean; stdcall;\nvar\n LHDesktop: HWND;\n LHParent: HWND;\n LExStyle: DWORD;\n\n AppClassName: array[0..255] of char;\n\n Cloaked: Cardinal;\n\n titlelen: Integer;\n title: String;\nbegin\n\n LHDesktop:=GetDesktopWindow;\n\n GetClassName(LHWindow, AppClassName, 255);\n LHParent:=GetWindowLong(LHWindow,GWL_HWNDPARENT);\n LExStyle:=GetWindowLong(LHWindow,GWL_EXSTYLE);\n\n if AppClassName = 'ApplicationFrameWindow' then\n DwmGetWindowAttribute(LHWindow, DWMWA_CLOAKED, @cloaked, sizeof(Cardinal))\n else\n cloaked := DWM_NORMAL_APP_NOT_CLOAKED;\n\n if IsWindowVisible(LHWindow)\n and (AppClassName <> 'Windows.UI.Core.CoreWindow')\n and ( (cloaked = DWM_NOT_CLOAKED) or (cloaked = DWM_NORMAL_APP_NOT_CLOAKED) )\n and ( (LHParent=0) or (LHParent=LHDesktop) )\n and (Application.Handle<>LHWindow)\n and ((LExStyle and WS_EX_TOOLWINDOW = 0) or (LExStyle and WS_EX_APPWINDOW <> 0))\n then\n begin\n titlelen := GetWindowTextLength(LHWindow);\n SetLength(title, titlelen);\n GetWindowText(LHWindow, PChar(title), titlelen + 1);\n { add each to a list }\n But.ListBox1.Items.Add(title);\n { also add each HWND to the list too, later switch using SwitchToThisWindow }\n { ... }\n end;\n\n\n Result := True;\nend;\n"
},
{
"answer_id": 62126899,
"author": "Frogfund",
"author_id": 13656345,
"author_profile": "https://Stackoverflow.com/users/13656345",
"pm_score": 1,
"selected": false,
"text": " public static bool IsAltTabWindow(IntPtr hWnd)\n {\n const uint WS_EX_TOOLWINDOW = 0x00000080;\n const uint DWMWA_CLOAKED = 14;\n\n // It must be a visible Window\n if (!IsWindowVisible(hWnd)) return false;\n\n // It must not be a Tool bar window\n WINDOWINFO winInfo = new WINDOWINFO(true);\n GetWindowInfo(hWnd, ref winInfo); \n if ((winInfo.dwExStyle & WS_EX_TOOLWINDOW) != 0) return false;\n\n // It must not be a cloaked window\n uint CloakedVal;\n DwmGetWindowAttribute(hWnd, DWMWA_CLOAKED, out CloakedVal, sizeof(uint));\n return CloakedVal == 0;\n }\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,506
|
<p>This may not be possible, but I figured I'd ask...</p>
<p>Is there any way anyone can think of to track whether or not an automatic variable has been deleted without modifying the class of the variable itself? For example, consider this code:</p>
<pre><code>const char* pStringBuffer;
{
std::string sString( "foo" );
pStringBuffer = sString.c_str();
}
</code></pre>
<p>Obviously, after the block, pStringBuffer is a dangling pointer which may or may not be valid. What I would like is a way to have a wrapper class which contains pStringBuffer (with a casting operator for const char*), but asserts that the variable it's referencing is still valid. By changing the type of the referenced variable I can certainly do it (boost shared_ptr/weak_ptr, for example), but I would like to be able to do it without imposing restrictions on the referenced type.</p>
<p>Some thoughts:</p>
<ul>
<li>I'll probably need to change the assignment syntax to include the referenced variable (which is fine)</li>
<li>I might be able to look at the stack pointer to detect if my wrapper class was allocated "later" than the referenced class, but this seems hacky and not standard (C++ doesn't define stack behavior). It could work, though.</li>
</ul>
<p>Thoughts / brilliant solutions?</p>
|
[
{
"answer_id": 210593,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 0,
"selected": false,
"text": "new delete operator new operator delete"
},
{
"answer_id": 210698,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 0,
"selected": false,
"text": "X<const char*> pStringBuffer;\n{\n std::string sString( \"foo\" );\n Trick trick(pStringBuffer).set(sString.c_str());\n} // trick goes out of scope; its destructor marks pStringBuffer as invalid\n X<const char*> pStringBuffer;\n{\n std::string sString( \"foo\" );\n {\n Trick trick(pStringBuffer).set(sString.c_str());\n } // trick goes out of scope; its destructor marks pStringBuffer as invalid\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26240/"
] |
210,509
|
<p>I have a bunch of records in several tables in a database that have a "process number" field, that's basically a number, but I have to store it as a string both because of some legacy data that has stuff like "89a" as a number and some numbering system that requires that process numbers be represented as number/year.</p>
<p>The problem arises when I try to order the processes by number. I get stuff like:</p>
<ul>
<li>1</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
<p>And the other problem is when I need to add a new process. The new process' number should be the biggest existing number incremented by one, and for that I would need a way to order the existing records by number.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 210521,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 1,
"selected": false,
"text": "SELECT process_order FROM your_table ORDER BY process_order + 0 ASC\n"
},
{
"answer_id": 210546,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 0,
"selected": false,
"text": "select * from table order by cast(field AS UNSIGNED);\n"
},
{
"answer_id": 210605,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "create table process_ordering ( processNumber varchar(N), processOrder int )\n select my_processes.*\nfrom my_processes\n inner join process_ordering on my_process.processNumber = process_ordering.processNumber\norder by process_ordering.processOrder\n"
},
{
"answer_id": 211127,
"author": "6eorge Jetson",
"author_id": 23422,
"author_profile": "https://Stackoverflow.com/users/23422",
"pm_score": 1,
"selected": false,
"text": "\nCREATE TABLE tblLegacyFormatRegularExpressionMaster(\n LegacyFormatId int,\n LegacyFormatName varchar(50),\n RegularExpression varchar(max)\n)\n"
},
{
"answer_id": 211312,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 1,
"selected": false,
"text": "CHAR VARCHAR CHECK CHECK (process_number LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][ab ]')\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
] |
210,515
|
<p>Assume a table with the following columns:</p>
<p><code>pri_id</code>, <code>item_id</code>, <code>comment</code>, <code>date</code></p>
<p>What I want to have is a SQL query that will delete any records, for a specific <code>item_id</code> that are older than a given date, BUT only as long as there are more than 15 rows for that <code>item_id</code>.</p>
<p>This will be used to purge out comment records older than 1 year for the items but I still want to keep at least 15 records at any given time. This way if I had one comment for 10 years it would never get deleted but if I had 100 comments over the last 5 days I'd only keep the newest 15 records. These are of course arbitrary record counts and date timeframes for this example.</p>
<p>I'd like to find a very generic way of doing this that would work in mysql, oracle, postgres etc. I'm using phps adodb library for DB abstraction so I'd like it to work well with that if possible.</p>
|
[
{
"answer_id": 210532,
"author": "Robert C. Barth",
"author_id": 9209,
"author_profile": "https://Stackoverflow.com/users/9209",
"pm_score": 4,
"selected": true,
"text": "delete\nfrom\n MyTable\nwhere\n item_id in\n (\n select\n item_id\n from\n MyTable\n group by\n item_id\n having\n count(item_id) > 15\n )\n and\n Date < @tDate\n"
},
{
"answer_id": 210540,
"author": "Jeremy",
"author_id": 9266,
"author_profile": "https://Stackoverflow.com/users/9266",
"pm_score": 0,
"selected": false,
"text": "DELETE\n [MyTable]\nWHERE\n [item_id] = 100 and\n (SELECT COUNT(*) FROM [MyTable] WHERE [item_id] = 100) > 15\n"
},
{
"answer_id": 210549,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 2,
"selected": false,
"text": " DELETE\n FROM CommentTable\n WHERE CommentId NOT IN (\n SELECT TOP 15 CommentId\n FROM CommentTable\n WHERE ItemId=@ItemId\n AND CommentDate < @Date\n ORDER BY CommentDate DESC\n )\n AND ItemId=@ItemId\n AND CommentDate < @Date\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14230/"
] |
210,518
|
<p>What do I use to search for multiple words in a string? I would like the logical operation to be AND so that all the words are in the string somewhere. I have a bunch of nonsense paragraphs and one plain English paragraph, and I'd like to narrow it down by specifying a couple common words like, "the" and "and", but would like it match all words I specify.</p>
|
[
{
"answer_id": 210539,
"author": "brasskazoo",
"author_id": 6340,
"author_profile": "https://Stackoverflow.com/users/6340",
"pm_score": 2,
"selected": false,
"text": "\\b(word1|word2)\\b(\\w+\\b)*(word1|word2)\\b(\\w+\\b)*\\.\n \\b"
},
{
"answer_id": 210565,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 2,
"selected": false,
"text": "AND ^(?=.*?\\b(?:word1)\\b)(?=.*?\\b(?:word2)\\b)(?=.*?\\b(?:word3)\\b)\n OR ^(?=.*?\\b(?:word1|word2|word3)\\b\n^(?=.*?\\b(?:word1)\\b)|^(?=.*?\\b(?:word2)\\b)|^(?=.*?\\b(?:word3)\\b)\n"
},
{
"answer_id": 210577,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "my @paragraphs = split(/\\n/,$text);\nfor my $p (@paragraphs) {\n if ($p =~ m/\\bthe\\b|\\band\\b|\\ban\\b|\\bin\\b|\\bon\\b|\\bthat\\b|\\bis\\b|\\bare\\b|th|sh|ough|augh|ing\\b|tion\\b|ed\\b|age\\b|’s\\b|’ve\\b|n’t\\b|’d\\b/) {\n print \"Probable english\\n$p\\n\";\n }\n}\n"
},
{
"answer_id": 268988,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "^(?=.*\\bword1\\b)(?=.*\\bword2\\b)(?=.*\\bword3\\b)\n \\b ?="
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
210,522
|
<p>I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...</p>
<p>So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the Entry widget i only get mouse events when inside the Entry widget.</p>
<p>How can I accomplish generate events for when a widget loses cursor focus?</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 225834,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 3,
"selected": false,
"text": "from Tkinter import *\n\ndef main():\n global text\n\n root=Tk()\n\n l1=Label(root,text=\"Field 1:\")\n l2=Label(root,text=\"Field 2:\")\n t1=Text(root,height=4,width=40)\n e1=Entry(root)\n e2=Entry(root)\n l1.grid(row=0,column=0,sticky=\"e\")\n e1.grid(row=0,column=1,sticky=\"ew\")\n l2.grid(row=1,column=0,sticky=\"e\")\n e2.grid(row=1,column=1,sticky=\"ew\")\n t1.grid(row=2,column=0,columnspan=2,sticky=\"nw\")\n\n root.grid_columnconfigure(1,weight=1)\n root.grid_rowconfigure(2,weight=1)\n\n root.bind_class(\"Entry\",\"<FocusOut>\",focusOutHandler)\n root.bind_class(\"Entry\",\"<FocusIn>\",focusInHandler)\n\n text = t1\n root.mainloop()\n\ndef focusInHandler(event):\n text.insert(\"end\",\"FocusIn %s\\n\" % event.widget)\n text.see(\"end\")\n\ndef focusOutHandler(event):\n text.insert(\"end\",\"FocusOut %s\\n\" % event.widget)\n text.see(\"end\")\n\n\nif __name__ == \"__main__\":\n main();\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,541
|
<p>The scenario: 2 user controls (foo.ascx and fum.ascx)</p>
<p>foo has a method that would really like to access a property from fum. They live on the same page, but I can't find a very simple way to accomplish this sort of communication. </p>
<p>Any ideas?</p>
|
[
{
"answer_id": 210571,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "OnMyPropertyValueChanged"
},
{
"answer_id": 210592,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "private Control findControl(Control root, string id) \n{ \n if (root.ID == id)\n { \n return root; \n } \n\n foreach (Control c in root.Controls) \n { \n Control t = findControl(c, id); \n if (t != null) \n { \n return t; \n } \n } \n\n return null; \n}\n public FunkyUserControl : UserControl\n{\n private List<UserControl> subscribedControls;\n\n public List<UserControl> Subscribers\n {\n get { return subscribedControls;}\n }\n\n public void SubscribeTo(UserControl control)\n {\n subscribedControls.Add(control);\n }\n}\n webControl1.SubscribeTo(webControl2);\nwebControl2.SubscribeTo(webControl1);\n"
},
{
"answer_id": 529171,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "FindControl Foo's Parent 'From within foo...call this code<br>\nDim objParent As Object<br>\nDim lngPropID As Long<br>\n\nobjParent = Me.Parent.FindControl(\"fum\")<br>\nlngPropID= objParent.PropID 'public property PropID on fum<br>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,564
|
<p>Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepared statement? For debugging purposes this would be extremely useful.</p>
|
[
{
"answer_id": 210693,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 8,
"selected": true,
"text": "081016 16:51:28 2 Query prepare s1 from 'select * from foo where i = ?'\n 2 Prepare [2] select * from foo where i = ?\n081016 16:51:39 2 Query set @a =1\n081016 16:51:47 2 Query execute s1 using @a\n 2 Execute [2] select * from foo where i = 1\n"
},
{
"answer_id": 1376838,
"author": "bigwebguy",
"author_id": 168256,
"author_profile": "https://Stackoverflow.com/users/168256",
"pm_score": 7,
"selected": false,
"text": "/**\n * Replaces any parameter placeholders in a query with the value of that\n * parameter. Useful for debugging. Assumes anonymous parameters from \n * $params are are in the same order as specified in $query\n *\n * @param string $query The sql query with parameter placeholders\n * @param array $params The array of substitution parameters\n * @return string The interpolated query\n */\npublic static function interpolateQuery($query, $params) {\n $keys = array();\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n } else {\n $keys[] = '/[?]/';\n }\n }\n\n $query = preg_replace($keys, $params, $query, 1, $count);\n\n #trigger_error('replaced '.$count.' keys');\n\n return $query;\n}\n"
},
{
"answer_id": 8403150,
"author": "Mike",
"author_id": 1083889,
"author_profile": "https://Stackoverflow.com/users/1083889",
"pm_score": 5,
"selected": false,
"text": "/**\n * Replaces any parameter placeholders in a query with the value of that\n * parameter. Useful for debugging. Assumes anonymous parameters from \n * $params are are in the same order as specified in $query\n *\n * @param string $query The sql query with parameter placeholders\n * @param array $params The array of substitution parameters\n * @return string The interpolated query\n */\npublic function interpolateQuery($query, $params) {\n $keys = array();\n $values = $params;\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n } else {\n $keys[] = '/[?]/';\n }\n\n if (is_string($value))\n $values[$key] = \"'\" . $value . \"'\";\n\n if (is_array($value))\n $values[$key] = \"'\" . implode(\"','\", $value) . \"'\";\n\n if (is_null($value))\n $values[$key] = 'NULL';\n }\n\n $query = preg_replace($keys, $values, $query);\n\n return $query;\n}\n"
},
{
"answer_id": 12015992,
"author": "Chris Go",
"author_id": 393134,
"author_profile": "https://Stackoverflow.com/users/393134",
"pm_score": 3,
"selected": false,
"text": "/**\n * Replaces any parameter placeholders in a query with the value of that\n * parameter. Useful for debugging. Assumes anonymous parameters from \n * $params are are in the same order as specified in $query\n *\n * @param string $query The sql query with parameter placeholders\n * @param array $params The array of substitution parameters\n * @return string The interpolated query\n */\npublic function interpolateQuery($query, $params) {\n $keys = array();\n $values = $params;\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n } else {\n $keys[] = '/[?]/';\n }\n\n if (is_array($value))\n $values[$key] = implode(',', $value);\n\n if (is_null($value))\n $values[$key] = 'NULL';\n }\n // Walk the array to see if we can add single-quotes to strings\n array_walk($values, create_function('&$v, $k', 'if (!is_numeric($v) && $v!=\"NULL\") $v = \"\\'\".$v.\"\\'\";'));\n\n $query = preg_replace($keys, $values, $query, 1, $count);\n\n return $query;\n}\n"
},
{
"answer_id": 23726095,
"author": "Noah Heck",
"author_id": 2422852,
"author_profile": "https://Stackoverflow.com/users/2422852",
"pm_score": 3,
"selected": false,
"text": "bindParam() bindValue() parent::bindParam() bindValue() execute() E_PDOStatement->fullQuery"
},
{
"answer_id": 24911732,
"author": "Jimmy Kane",
"author_id": 1857292,
"author_profile": "https://Stackoverflow.com/users/1857292",
"pm_score": 4,
"selected": false,
"text": "PDOStatement::debugDumpParams <?php\n/* Execute a prepared statement by binding PHP variables */\n$calories = 150;\n$colour = 'red';\n$sth = $dbh->prepare('SELECT name, colour, calories\n FROM fruit\n WHERE calories < :calories AND colour = :colour');\n$sth->bindParam(':calories', $calories, PDO::PARAM_INT);\n$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);\n$sth->execute();\n\n$sth->debugDumpParams();\n\n?>\n"
},
{
"answer_id": 33932131,
"author": "vee",
"author_id": 128761,
"author_profile": "https://Stackoverflow.com/users/128761",
"pm_score": -1,
"selected": false,
"text": "SELECT * FROM `an_modules` AS `m` LEFT JOIN `an_module_sites` AS `ms` ON m.module_id = ms.module_id WHERE 1 AND `module_enable` = :module_enable AND `site_id` = :site_id AND (`module_system_name` LIKE :search OR `module_version` LIKE :search)\n public function interpolateQuery($query, $params) {\n $keys = array();\n $values = $params;\n $values_limit = [];\n\n $words_repeated = array_count_values(str_word_count($query, 1, ':_'));\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n $values_limit[$key] = (isset($words_repeated[':'.$key]) ? intval($words_repeated[':'.$key]) : 1);\n } else {\n $keys[] = '/[?]/';\n $values_limit = [];\n }\n\n if (is_string($value))\n $values[$key] = \"'\" . $value . \"'\";\n\n if (is_array($value))\n $values[$key] = \"'\" . implode(\"','\", $value) . \"'\";\n\n if (is_null($value))\n $values[$key] = 'NULL';\n }\n\n if (is_array($values)) {\n foreach ($values as $key => $val) {\n if (isset($values_limit[$key])) {\n $query = preg_replace(['/:'.$key.'/'], [$val], $query, $values_limit[$key], $count);\n } else {\n $query = preg_replace(['/:'.$key.'/'], [$val], $query, 1, $count);\n }\n }\n unset($key, $val);\n } else {\n $query = preg_replace($keys, $values, $query, 1, $count);\n }\n unset($keys, $values, $values_limit, $words_repeated);\n\n return $query;\n}\n"
},
{
"answer_id": 34681244,
"author": "Markos F",
"author_id": 2076316,
"author_profile": "https://Stackoverflow.com/users/2076316",
"pm_score": -1,
"selected": false,
"text": "public function interpolateQuery($query, $params) {\n$keys = array();\n $length = count($params)-1;\n for ($i = $length; $i >=0; $i--) {\n $query = str_replace(':binding_'.(string)$i, '\\''.$params[$i]['val'].'\\'', $query);\n }\n // $query = str_replace('SQL_CALC_FOUND_ROWS', '', $query, $count);\n return $query;\n"
},
{
"answer_id": 38049697,
"author": "ducminh1903",
"author_id": 3254564,
"author_profile": "https://Stackoverflow.com/users/3254564",
"pm_score": -1,
"selected": false,
"text": "/**\n * \n * @param string $str\n * @return string\n */\npublic function quote($str) {\n if (!is_array($str)) {\n return $this->pdo->quote($str);\n } else {\n $str = implode(',', array_map(function($v) {\n return $this->quote($v);\n }, $str));\n\n if (empty($str)) {\n return 'NULL';\n }\n\n return $str;\n }\n}\n\n/**\n * \n * @param string $query\n * @param array $params\n * @return string\n * @throws Exception\n */\npublic function interpolateQuery($query, $params) {\n $ps = preg_split(\"/'/is\", $query);\n $pieces = [];\n $prev = null;\n foreach ($ps as $p) {\n $lastChar = substr($p, strlen($p) - 1);\n\n if ($lastChar != \"\\\\\") {\n if ($prev === null) {\n $pieces[] = $p;\n } else {\n $pieces[] = $prev . \"'\" . $p;\n $prev = null;\n }\n } else {\n $prev .= ($prev === null ? '' : \"'\") . $p;\n }\n }\n\n $arr = [];\n $indexQuestionMark = -1;\n $matches = [];\n\n for ($i = 0; $i < count($pieces); $i++) {\n if ($i % 2 !== 0) {\n $arr[] = \"'\" . $pieces[$i] . \"'\";\n } else {\n $st = '';\n $s = $pieces[$i];\n while (!empty($s)) {\n if (preg_match(\"/(\\?|:[A-Z0-9_\\-]+)/is\", $s, $matches, PREG_OFFSET_CAPTURE)) {\n $index = $matches[0][1];\n $st .= substr($s, 0, $index);\n $key = $matches[0][0];\n $s = substr($s, $index + strlen($key));\n\n if ($key == '?') {\n $indexQuestionMark++;\n if (array_key_exists($indexQuestionMark, $params)) {\n $st .= $this->quote($params[$indexQuestionMark]);\n } else {\n throw new Exception('Wrong params in query at ' . $index);\n }\n } else {\n if (array_key_exists($key, $params)) {\n $st .= $this->quote($params[$key]);\n } else {\n throw new Exception('Wrong params in query with key ' . $key);\n }\n }\n } else {\n $st .= $s;\n $s = null;\n }\n }\n $arr[] = $st;\n }\n }\n\n return implode('', $arr);\n}\n"
},
{
"answer_id": 42144012,
"author": "Otamay",
"author_id": 1644498,
"author_profile": "https://Stackoverflow.com/users/1644498",
"pm_score": 3,
"selected": false,
"text": "class DebugPDOStatement extends \\PDOStatement{\n private $bound_variables=array();\n protected $pdo;\n\n protected function __construct($pdo) {\n $this->pdo = $pdo;\n }\n\n public function bindValue($parameter, $value, $data_type=\\PDO::PARAM_STR){\n $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>$value);\n return parent::bindValue($parameter, $value, $data_type);\n }\n\n public function bindParam($parameter, &$variable, $data_type=\\PDO::PARAM_STR, $length=NULL , $driver_options=NULL){\n $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>&$variable);\n return parent::bindParam($parameter, $variable, $data_type, $length, $driver_options);\n }\n\n public function debugBindedVariables(){\n $vars=array();\n\n foreach($this->bound_variables as $key=>$val){\n $vars[$key] = $val->value;\n\n if($vars[$key]===NULL)\n continue;\n\n switch($val->type){\n case \\PDO::PARAM_STR: $type = 'string'; break;\n case \\PDO::PARAM_BOOL: $type = 'boolean'; break;\n case \\PDO::PARAM_INT: $type = 'integer'; break;\n case \\PDO::PARAM_NULL: $type = 'null'; break;\n default: $type = FALSE;\n }\n\n if($type !== FALSE)\n settype($vars[$key], $type);\n }\n\n if(is_numeric(key($vars)))\n ksort($vars);\n\n return $vars;\n }\n\n public function debugQuery(){\n $queryString = $this->queryString;\n\n $vars=$this->debugBindedVariables();\n $params_are_numeric=is_numeric(key($vars));\n\n foreach($vars as $key=>&$var){\n switch(gettype($var)){\n case 'string': $var = \"'{$var}'\"; break;\n case 'integer': $var = \"{$var}\"; break;\n case 'boolean': $var = $var ? 'TRUE' : 'FALSE'; break;\n case 'NULL': $var = 'NULL';\n default:\n }\n }\n\n if($params_are_numeric){\n $queryString = preg_replace_callback( '/\\?/', function($match) use( &$vars) { return array_shift($vars); }, $queryString);\n }else{\n $queryString = strtr($queryString, $vars);\n }\n\n echo $queryString.PHP_EOL;\n }\n}\n\n\nclass DebugPDO extends \\PDO{\n public function __construct($dsn, $username=\"\", $password=\"\", $driver_options=array()) {\n $driver_options[\\PDO::ATTR_STATEMENT_CLASS] = array('DebugPDOStatement', array($this));\n $driver_options[\\PDO::ATTR_PERSISTENT] = FALSE;\n parent::__construct($dsn,$username,$password, $driver_options);\n }\n}\n $dbh = new DebugPDO('mysql:host=localhost;dbname=test;','user','pass');\n\n$var='user_test';\n$sql=$dbh->prepare(\"SELECT user FROM users WHERE user = :test\");\n$sql->bindValue(':test', $var, PDO::PARAM_STR);\n$sql->execute();\n\n$sql->debugQuery();\nprint_r($sql->debugBindedVariables());\n"
},
{
"answer_id": 49141711,
"author": "JacopoStanchi",
"author_id": 8145618,
"author_profile": "https://Stackoverflow.com/users/8145618",
"pm_score": 4,
"selected": false,
"text": "//Connection to the database\n$co = new PDO('mysql:dbname=myDB;host=localhost','root','');\n//We allow to print the errors whenever there is one\n$co->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n//We create our prepared statement\n$stmt = $co->prepare(\"ELECT * FROM Person WHERE age=:age\"); //I removed the 'S' of 'SELECT'\n$stmt->bindValue(':age','18',PDO::PARAM_STR);\ntry {\n $stmt->execute();\n} catch (PDOException $e) {\n echo $e->getMessage();\n}\n"
},
{
"answer_id": 53966487,
"author": "Sakura Kinomoto",
"author_id": 4537662,
"author_profile": "https://Stackoverflow.com/users/4537662",
"pm_score": 1,
"selected": false,
"text": "/**\n * Replaces any parameter placeholders in a query with the value of that\n * parameter. Useful for debugging. Assumes anonymous parameters from \n * $params are are in the same order as specified in $query\n *\n * @param string $query The sql query with parameter placeholders\n * @param array $params The array of substitution parameters\n * @return string The interpolated query\n */\npublic function interpolateQuery($query, $params) {\n $keys = array();\n $values = $params;\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n } else {\n $keys[] = '/[?]/';\n }\n\n if (is_array($value))\n $values[$key] = implode(',', $value);\n\n if (is_null($value))\n $values[$key] = 'NULL';\n }\n // Walk the array to see if we can add single-quotes to strings\n array_walk($values, function(&$v, $k) { if (!is_numeric($v) && $v != \"NULL\") $v = \"\\'\" . $v . \"\\'\"; });\n\n $query = preg_replace($keys, $values, $query, 1, $count);\n\n return $query;\n}\n"
},
{
"answer_id": 56800829,
"author": "kurdtpage",
"author_id": 600852,
"author_profile": "https://Stackoverflow.com/users/600852",
"pm_score": 2,
"selected": false,
"text": "sprintf(str_replace('?', '\"%s\"', $sql), ...$params); function mysqli_prepared_query($link, $sql, $types='', $params=array()) {\n echo sprintf(str_replace('?', '\"%s\"', $sql), ...$params);\n //prepare, bind, execute\n}\n\n$link = new mysqli($server, $dbusername, $dbpassword, $database);\n$sql = \"SELECT firstname, lastname FROM users WHERE userage >= ? AND favecolor = ?\";\n$types = \"is\"; //integer and string\n$params = array(20, \"Brown\");\n\nif(!$qry = mysqli_prepared_query($link, $sql, $types, $params)){\n echo \"Failed\";\n} else {\n echo \"Success\";\n}\n"
},
{
"answer_id": 66470138,
"author": "Magnus",
"author_id": 930640,
"author_profile": "https://Stackoverflow.com/users/930640",
"pm_score": 2,
"selected": false,
"text": "? :foo NULL int float bool \"?\" \":foo\" function interpolateSQL(PDO $pdo, string $query, array $params) : string {\n $s = chr(2); // Escape sequence for start of placeholder\n $e = chr(3); // Escape sequence for end of placeholder\n $keys = [];\n $values = [];\n\n // Make sure we use escape sequences that are not present in any value\n // to escape the placeholders.\n foreach ($params as $key => $value) {\n while( mb_stripos($value, $s) !== false ) $s .= $s;\n while( mb_stripos($value, $e) !== false ) $e .= $e;\n }\n \n \n foreach ($params as $key => $value) {\n // Build a regular expression for each parameter\n $keys[] = is_string($key) ? \"/$s:$key$e/\" : \"/$s\\?$e/\";\n\n // Treat each value depending on what type it is. \n // While PDO::quote() has a second parameter for type hinting, \n // it doesn't seem reliable (at least for the SQLite driver).\n if( is_null($value) ){\n $values[$key] = 'NULL';\n }\n elseif( is_int($value) || is_float($value) ){\n $values[$key] = $value;\n }\n elseif( is_bool($value) ){\n $values[$key] = $value ? 'true' : 'false';\n }\n else{\n $value = str_replace('\\\\', '\\\\\\\\', $value);\n $values[$key] = $pdo->quote($value);\n }\n }\n\n // Surround placehodlers with escape sequence, so we don't accidentally match\n // \"?\" or \":foo\" inside any of the values.\n $query = preg_replace(['/\\?/', '/(:[a-zA-Z0-9_]+)/'], [\"$s?$e\", \"$s$1$e\"], $query);\n\n // Replace placeholders with actual values\n $query = preg_replace($keys, $values, $query, 1, $count);\n\n // Verify that we replaced exactly as many placeholders as there are keys and values\n if( $count !== count($keys) || $count !== count($values) ){\n throw new \\Exception('Number of replacements not same as number of keys and/or values');\n }\n\n return $query;\n }\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
210,567
|
<p>Whats the best practice for setting up package structures in a Java Web Application?</p>
<p>How would you setup your src, unit test code, etc?</p>
|
[
{
"answer_id": 52802639,
"author": "Raj",
"author_id": 5107365,
"author_profile": "https://Stackoverflow.com/users/5107365",
"pm_score": 3,
"selected": false,
"text": "The way I usually organise is\n- src\n - main\n - java\n - groovy\n - resources\n - test\n - java\n - groovy\n- lib\n- build\n - test \n - reports\n - classes\n- doc\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24717/"
] |
210,590
|
<p>Why is it that <code>scanf()</code> needs the <code>l</code> in "<code>%lf</code>" when reading a <code>double</code>, when <code>printf()</code> can use "<code>%f</code>" regardless of whether its argument is a <code>double</code> or a <code>float</code>?</p>
<p>Example code:</p>
<pre><code>double d;
scanf("%lf", &d);
printf("%f", d);
</code></pre>
|
[
{
"answer_id": 210591,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 9,
"selected": true,
"text": "%lf %lg %le %la"
},
{
"answer_id": 210595,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 4,
"selected": false,
"text": "scanf &d printf double"
},
{
"answer_id": 28222471,
"author": "AnT stands with Russia",
"author_id": 187690,
"author_profile": "https://Stackoverflow.com/users/187690",
"pm_score": 5,
"selected": false,
"text": "printf scanf %f float %lf double %Lf long double float double printf %f %lf printf %lf float %f double %f printf double %lf printf double %f float"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
210,601
|
<p>In C#, what is the best way to access a property of the derived class when the generic list contains just the base class.</p>
<pre><code>public class ClassA : BaseClass
{
public object PropertyA { get; set; }
}
public class ClassB: BaseClass
{
public object PropertyB { get; set; }
}
public class BaseClass
{
}
public void Main
{
List<BaseClass> MyList = new List<BaseClass>();
ClassA a = new ClassA();
ClassB b = new ClassB();
MyList.Add(a);
MyList.Add(b);
for(int i = 0; i < MyList.Count; i++)
{
//I would like to access PropertyA abd PropertyB from the derived classes
}
}
</code></pre>
|
[
{
"answer_id": 210615,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": " BaseClass o = MyList[i];\n if (o is ClassB)\n {\n object k = ((ClassB)o).PropertyB;\n }\n if (o is ClassA))\n {\n object j = ((ClassA)o).PropertyA;\n }\n"
},
{
"answer_id": 210617,
"author": "tsimon",
"author_id": 1685,
"author_profile": "https://Stackoverflow.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "for(int i = 0; i < MyList.Count; i++)\n{\n BaseClass bc = MyList[i];\n ClassA a = bc as ClassA;\n ClassB b = bc as ClassB;\n bc.BaseClassMethod();\n if (a != null) {\n a.PropertyA;\n }\n if (b != null) {\n b.PropertyB;\n }\n}\n"
},
{
"answer_id": 210618,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "for (int i = 0; i < MyList.Count; i++)\n{\n if (MyList[i] is ClassA)\n {\n var a = ((ClassA)MyList[i]).PropertyA;\n // do stuff with a\n }\n\n if (MyList[i] is ClassB)\n {\n var b = ((ClassB)MyList[i]).PropertyB;\n // do stuff with b\n }\n}\n public class BaseClass\n{\n public virtual void DoStuff() { }\n}\n\npublic class ClassA : BaseClass\n{\n public object PropertyA { get; set; }\n\n public override void DoStuff() \n {\n // do stuff with PropertyA \n }\n}\n\npublic class ClassB : BaseClass\n{\n public object PropertyB { get; set; }\n\n public override void DoStuff() \n {\n // do stuff with PropertyB\n }\n}\n"
},
{
"answer_id": 210737,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 2,
"selected": false,
"text": " public static class MyBaseListExtensions\n {\n public static IEnumerable<ClassA> GetAllAs(this List<MyBaseClass> list)\n {\n foreach (var obj in list)\n {\n if (obj is ClassA)\n {\n yield return (ClassA)obj;\n }\n }\n }\n\n public static IEnumerable<ClassB> GetAllbs(this List<MyBaseClass> list)\n {\n foreach (var obj in list)\n {\n if (obj is ClassB)\n {\n yield return (ClassB)obj;\n }\n }\n }\n }\n private void button1_Click(object sender, EventArgs e)\n{\n ClassA a1 = new ClassA() { PropertyA = \"Tim\" };\n ClassA a2 = new ClassA() { PropertyA = \"Pip\" };\n ClassB b1 = new ClassB() { PropertyB = \"Alex\" };\n ClassB b2 = new ClassB() { PropertyB = \"Rachel\" };\n\n List<MyBaseClass> list = new List<MyBaseClass>();\n list.Add(a1);\n list.Add(a2);\n list.Add(b1);\n list.Add(b2);\n\n foreach (var a in list.GetAllAs())\n {\n listBox1.Items.Add(a.PropertyA);\n }\n\n foreach (var b in list.GetAllbs())\n {\n listBox2.Items.Add(b.PropertyB);\n }\n}\n"
},
{
"answer_id": 210746,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class ClassA : BaseClass\n{\n public override object PropertyA { get; set; }\n}\n\npublic class ClassB: BaseClass\n{\n public override object PropertyB { get; set; }\n}\n\npublic class BaseClass\n{\n public virtual object PropertyA { get; set; }\n public virtual object PropertyB { get; set; }\n}\n\npublic void Main\n{\n List<BaseClass> MyList = new List<BaseClass>();\n ClassA a = new ClassA();\n ClassB b = new ClassB();\n\n MyList.Add(a);\n MyList.Add(b);\n\n for(int i = 0; i < MyList.Count; i++)\n {\n // Do something here with the Property\n MyList[i].PropertyA;\n MyList[i].PropertyB; \n }\n}\n"
},
{
"answer_id": 211781,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<T> OfType<T>(this IEnumerable list)\n{\n foreach (var obj in list)\n {\n if (obj is T)\n yield return (T)obj;\n }\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
210,606
|
<p>Is there a way to invoke an external script or batch file from VC6 (and later) project files?</p>
<p>I have a background process that I need to kill before attempting to build certain projects (DLLS, executables) and haven't found a way to successfully do so from the project itself. I'd like simply to call a batch file with a taskkill command in it.</p>
<p>(Yes, I could run the batch file from a command line before building the projects, but I don't always remember to do so and having it done automatically would be more convenient and less irritating for the whole development team.)</p>
|
[
{
"answer_id": 210689,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 0,
"selected": false,
"text": "<!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n Other similar extension points exist, see Microsoft.Common.targets.\n<Target Name=\"BeforeBuild\">\n</Target>\n<Target Name=\"AfterBuild\">\n</Target>\n-->\n <Target Name=\"BeforeBuild\">\n <Exec Command=\"MyBatchFile.bat\" />\n</Target>\n"
},
{
"answer_id": 212723,
"author": "David",
"author_id": 28275,
"author_profile": "https://Stackoverflow.com/users/28275",
"pm_score": 1,
"selected": false,
"text": "set solutionDir=$(SolutionDir)\nset platformName=$(PlatformName)\nset configurationName=$(ConfigurationName)\n\ncall $(SolutionDir)PostBuild.bat\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,607
|
<p>I would like to know many minutes between 2 dates?</p>
<p>Example : Now - tommorow at the exact time would return me 1440.</p>
|
[
{
"answer_id": 210609,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": " DateTime date1 = DateTime.Now;\n DateTime date2 = DateTime.Now.AddDays(1);\n\n TimeSpan diff = date2.Subtract(date1);\n Console.WriteLine(diff.Minutes);\n"
},
{
"answer_id": 210611,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": -1,
"selected": false,
"text": "DateTime currentTime = DateTime.Now;\nDateTime tommorowTime = currentTime.AddDays(1);\nTimeSpan diffTime = tommorowTime - currentTime ;\nConsole.WriteLine(diffTime.TotalMinutes);\n"
},
{
"answer_id": 210619,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 5,
"selected": true,
"text": "DateTime dt1 = DateTime.Now;\nDateTime dt2 = DateTime.Now.AddDays(1);\n\nint diff = dt2.Subtract(dt1).TotalMinutes;\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
] |
210,616
|
<p>I'm reading this C++ open source code and I came to a constructor but I don't get it ( basically because I don't know C++ :P ) </p>
<p>I understand C and Java very well.</p>
<pre><code> TransparentObject::TransparentObject( int w, int x, int y, int z ) :
_someMethod( 0 ),
_someOtherMethod( 0 ),
_someOtherOtherMethod( 0 ),
_someMethodX( 0 )
{
int bla;
int bla;
}
</code></pre>
<p>As far I can "deduce" The first line only declares the construtor name, the "::" sounds like "belongs to" to me. And the code between {} is the constructor body it self. </p>
<p>I "think" what's after the paremeters and the first "{" are like methods default parameters or something, but I don't find a reasonable explanation on the web. Most of the C++ constructors that I found in the examples are almost identical to those in Java.</p>
<p>I'm I right in my assumptions? "::" is like belongs to, and the list after params and body are like "default args" or something?</p>
<p><strong>UPDATE:</strong>
Thanks for the answers.
May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body</p>
|
[
{
"answer_id": 210636,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "{}"
},
{
"answer_id": 210638,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 5,
"selected": true,
"text": "class foo{\nprivate:\n int x;\n int y;\npublic:\n foo(int _x, int _y) : x(_x), y(_y) {}\n}\n x y _x _y class foo : public bar{\n foo(int x, int y) : bar(x, y) {}\n};\n x y TransparentObject::TransparentObject( int w, int x, int y, int z ) : \n _someMethod( 0 ),\n _someOtherMethod( 0 ),\n _someOtherOtherMethod( 0 ),\n _someMethodX( 0 ) \n{\n int bla;\n int bla;\n}\n :: TransparentObject TransparentObject const"
},
{
"answer_id": 210641,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": false,
"text": "TransparentObject::TransparentObject( int w, int x, int y, int z )\n : \n _someMethod( 0 ),\n _someOtherMethod( 0 ),\n _someOtherOtherMethod( 0 ),\n _someMethodX( 0 )\n {\n int bla;\n int bla;\n}\n"
},
{
"answer_id": 329080,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 1,
"selected": false,
"text": "class A\n{\npublic:\n A();\nprivate:\n B _b;\n C& _c;\n};\n\nA::A( C& someC )\n{\n _c = someC; // this is illegal and won't compile. _c has to be initialized before we get inside the braces\n _b = B(NULL, 5, \"hello\"); // this is not illegal, but B might not have a default constructor or could have a very \n // expensive construction that shouldn't be done more than once\n}\n A::A( C& someC )\n: _b(NULL, 5, \"hello\") // ok, initializing _b by passing these arguments to its constructor\n, _c( someC ) // this reference to some instance of C is correctly initialized now\n{}\n"
},
{
"answer_id": 8104591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "m_b value m_a m_b m_a m_b m_b value m_b struct BadInitialiserListExample\n{\n BadInitialiserListExample(int value) :\n m_b(value),\n m_a(m_b) // <-- *BUG* this is actually executed first due to ordering below!\n {\n }\n\n int m_a;\n int m_b;\n};\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
210,620
|
<p>I have created HTTP handlers. </p>
<p>How do I create global variables for these handlers like I can with ASP.net web pages in global.asax?</p>
|
[
{
"answer_id": 210626,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 4,
"selected": true,
"text": "System.Web.HttpContext.Current.Application[\"MyGlobalVariable\"] = myValue;\n System.Web.HttpContext.Current.Items[\"MyGlobalVariable\"] = myValue;\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100768/"
] |
210,629
|
<p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p>
<p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]?</p>
<p>In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.</p>
<p>EDIT: the specific issue is this:</p>
<pre><code>>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
</code></pre>
|
[
{
"answer_id": 210707,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 4,
"selected": false,
"text": "from numpy import uint32\n"
},
{
"answer_id": 210740,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 6,
"selected": false,
"text": "c_uint32 >>> import ctypes\n>>> m = 0xFFFFFF00\n>>> ctypes.c_uint32(~m).value\n255L\n ~m"
},
{
"answer_id": 210747,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 7,
"selected": true,
"text": "0xFFFFFFFF >>> m = 0xFFFFFF00\n>>> allf = 0xFFFFFFFF\n>>> ~m & allf\n255L\n"
},
{
"answer_id": 211342,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "CIDR"
},
{
"answer_id": 34951075,
"author": "Maarten",
"author_id": 349760,
"author_profile": "https://Stackoverflow.com/users/349760",
"pm_score": 3,
"selected": false,
"text": ">>> 0xFFFFFF00 ^ 0xFFFFFFFF\n255\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18770/"
] |
210,637
|
<p>I have been looking at <a href="http://jquery.com/demo/thickbox/" rel="nofollow noreferrer">jQUery thickbox</a> for showing modal dialogs with images, it is great. But now I have the need to display a hidden div of content that contains an iFrame in a similar fashion, with a link to open the content. So I'd have something like this.</p>
<pre><code><a href="">Open window in Modal Dialog</a>
<div id="myContent">
<h1>Look at me!</h1>
<iframe src="http://www.google.com" />
</div>
</code></pre>
<p>And need to show it in the dialog. Is it possible?</p>
|
[
{
"answer_id": 210654,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 2,
"selected": false,
"text": "<div class=\"jqmWindow\" id=\"modalDialog\"> \n <iframe frameborder=\"0\" id=\"jqmContent\" src=\"\"> \n </iframe> \n</div>\n function showModal(url, height, width)\n{ \n var dialog = $('#modalDialog')\n .jqm({ \n onShow: function(h) {\n var $modal = $(h.w); \n var $modalContent = $(\"iframe\", $modal); \n $modalContent.html('').attr('src', url); \n if (height > 0) $modal.height(height); \n if (width > 0) $modal.width(width); \n h.w.show(); \n } \n }).jqmShow(); \n}\n\nfunction closeModal(postback)\n{\n $('#modalDialog').jqmHide();\n}\n"
},
{
"answer_id": 3310036,
"author": "Tahir Hassan",
"author_id": 288393,
"author_profile": "https://Stackoverflow.com/users/288393",
"pm_score": 0,
"selected": false,
"text": "wrap.bind('dragstart', function() { overlay.show(); })\n .bind('dragstop', function() { overlay.hide(); })\n .bind('resizestart', function() { overlay.show(); })\n .bind('resizestop', function() { overlay.hide(); });\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13279/"
] |
210,643
|
<p>I'd like to make a click event fire on an <code><input type="file"></code> tag programmatically.</p>
<p>Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.</p>
<p>I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.</p>
|
[
{
"answer_id": 3030174,
"author": "Romas",
"author_id": 365407,
"author_profile": "https://Stackoverflow.com/users/365407",
"pm_score": 8,
"selected": false,
"text": "<div style=\"display: block; width: 100px; height: 20px; overflow: hidden;\">\n<button style=\"width: 110px; height: 30px; position: relative; top: -5px; left: -5px;\"><a href=\"javascript: void(0)\">Upload File</a></button>\n<input type=\"file\" id=\"upload_input\" name=\"upload\" style=\"font-size: 50px; width: 120px; opacity: 0; filter:alpha(opacity=0); position: relative; top: -40px;; left: -20px\" />\n</div>\n"
},
{
"answer_id": 3552750,
"author": "McTrafik",
"author_id": 376737,
"author_profile": "https://Stackoverflow.com/users/376737",
"pm_score": 3,
"selected": false,
"text": "<a id=\"fileLink\" href=\"javascript:fileBrowse();\" onmouseover=\"fileMove();\">File Browse</a>\n <div id=\"uploadForm\" style=\"filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;\">\n <form method=\"POST\" enctype=\"multipart/form-data\">\n <input type=\"file\" name=\"file\" />\n </form>\n</div>\n function pageY(el) {\n var ot = 0;\n while (el && el.offsetParent != el) {\n ot += el.offsetTop ? el.offsetTop : 0;\n el = el.offsetParent;\n }\n return ot;\n}\n\nfunction pageX(el) {\n var ol = 0;\n while (el && el.offsetParent != el) {\n ol += el.offsetLeft ? el.offsetLeft : 0;\n el = el.offsetParent;\n }\n return ol;\n}\n\nfunction fileMove() {\n if (navigator.appName == \"Microsoft Internet Explorer\") {\n return; // Don't need to do this in IE. \n }\n var link = document.getElementById(\"fileLink\");\n var form = document.getElementById(\"uploadForm\");\n var x = pageX(link);\n var y = pageY(link);\n form.style.position = 'absolute';\n form.style.left = x + 'px';\n form.style.top = y + 'px';\n}\n\nfunction fileBrowse() {\n // This works in IE only. Doesn't do jack in FF. :( \n var browseField = document.getElementById(\"uploadForm\").file;\n browseField.click();\n}\n"
},
{
"answer_id": 6888810,
"author": "Florin Mogos",
"author_id": 871442,
"author_profile": "https://Stackoverflow.com/users/871442",
"pm_score": 6,
"selected": false,
"text": "$('#input_element').show();\n$('#input_element').focus();\n$('#input_element').click();\n$('#input_element').hide();\n click()"
},
{
"answer_id": 7373769,
"author": "Mat J",
"author_id": 219933,
"author_profile": "https://Stackoverflow.com/users/219933",
"pm_score": 2,
"selected": false,
"text": "<input type=\"file\" style=\"position:absolute;left:-999px;\" id=\"fileinput\" />\n<button id=\"addfiles\" >Add files</button>\n\n<script language=\"javascript\" type=\"text/javascript\">\n $(\"#addfiles\").click(function(){\n $(\"#fileinput\").click();\n });\n</script>\n"
},
{
"answer_id": 7548348,
"author": "DejanR",
"author_id": 636542,
"author_profile": "https://Stackoverflow.com/users/636542",
"pm_score": 1,
"selected": false,
"text": "#uploadtruefield {\n left: 225px;\n opacity: 0;\n position: absolute;\n right: 0;\n top: 266px;\n opacity:0;\n -moz-opacity:0;\n filter:alpha(opacity:0);\n width: 270px;\n z-index: 2;\n}\n\n.uploadmask {\n background:url(../img/browse.gif) no-repeat 100% 50%;\n}\n#uploadmaskfield{\n width:132px;\n}\n <div class=\"uploadmask\">\n <input id=\"uploadmaskfield\" type=\"text\" name=\"uploadmaskfield\">\n</div>\n<input id=\"uploadtruefield\" type=\"file\" onchange=\"$('#uploadmaskfield').val(this.value)\" >\n"
},
{
"answer_id": 8354389,
"author": "Kurt",
"author_id": 995369,
"author_profile": "https://Stackoverflow.com/users/995369",
"pm_score": 2,
"selected": false,
"text": "<input type=\"button\"> \"onClick\" $('#id_of_component').click();\n document.getElementById('id_of_component').click();\n"
},
{
"answer_id": 8644637,
"author": "Linblow",
"author_id": 1117627,
"author_profile": "https://Stackoverflow.com/users/1117627",
"pm_score": 3,
"selected": false,
"text": "click display: none; #fileInput {\n visibility: hidden;\n position: absolute;\n top: 0;\n left: -5000px;\n}\n"
},
{
"answer_id": 8924420,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "inputElement.click() <input type=\"file\" /> inputElement.style.display !== 'none'"
},
{
"answer_id": 9606494,
"author": "CodeChap",
"author_id": 195192,
"author_profile": "https://Stackoverflow.com/users/195192",
"pm_score": 2,
"selected": false,
"text": "$(\"<input type='file' class='ui-helper-hidden-accessible' />\").appendTo(\"body\").focus().trigger('click');\n"
},
{
"answer_id": 12822631,
"author": "Leon Creatini",
"author_id": 1735312,
"author_profile": "https://Stackoverflow.com/users/1735312",
"pm_score": 3,
"selected": false,
"text": "$(document).one('mousemove', function() { $(element).trigger('click') } );\n"
},
{
"answer_id": 12826822,
"author": "SpYk3HH",
"author_id": 900807,
"author_profile": "https://Stackoverflow.com/users/900807",
"pm_score": 2,
"selected": false,
"text": "<div class=\"file-input wrapper\">\n <input id=\"inpFile0\" type=\"file\" class=\"file-input control\" />\n <div class=\"file-input content\">\n <label id=\"inpFileOutput0\" for=\"inpFileButton\" class=\"file-input output\">Click Here</label>\n <input id=\"inpFileButton0\" type=\"button\" class=\"file-input button\" value=\"Select File\" />\n </div>\n</div>\n .file-test-area {\n border: 1px solid;\n margin: .5em;\n padding: 1em;\n}\n.file-input {\n cursor: pointer !important;\n}\n.file-input * {\n cursor: pointer !important;\n display: inline-block;\n}\n.file-input.wrapper {\n display: inline-block;\n font-size: 14px;\n height: auto;\n overflow: hidden;\n position: relative;\n width: auto;\n}\n.file-input.control {\n -moz-opacity:0 ;\n filter:alpha(opacity: 0);\n opacity: 0;\n\n height: 100%;\n position: absolute;\n text-align: right;\n width: 100%;\n z-index: 2;\n}\n.file-input.content {\n position: relative;\n top: 0px;\n left: 0px;\n z-index: 1;\n}\n.file-input.output {\n background-color: #FFC;\n font-size: .8em;\n padding: .2em .2em .2em .4em;\n text-align: center;\n width: 10em;\n}\n.file-input.button {\n border: none;\n font-weight: bold;\n margin-left: .25em;\n padding: 0 .25em;\n}\n var inp = document.getElementsByTagName('input');\nfor (var i=0;i<inp.length;i++) {\n if (inp[i].type != 'file') continue;\n inp[i].relatedElement = inp[i].parentNode.getElementsByTagName('label')[0];\n inp[i].onchange /*= inp[i].onmouseout*/ = function () {\n this.relatedElement.innerHTML = this.value;\n };\n};\n"
},
{
"answer_id": 13784146,
"author": "McLosys Creative",
"author_id": 1442566,
"author_profile": "https://Stackoverflow.com/users/1442566",
"pm_score": 1,
"selected": false,
"text": "<input type=\"file\" id=\"upload\" name=\"upload\" style=\"visibility: hidden; width: 1px; height: 1px\" multiple />\n<a href=\"\" onclick=\"document.getElementById('upload').click(); return false\">Upload</a>\n"
},
{
"answer_id": 20810390,
"author": "kop",
"author_id": 3141026,
"author_profile": "https://Stackoverflow.com/users/3141026",
"pm_score": 2,
"selected": false,
"text": "<script>\nclick=function(element){\n if(element!=null){\n try {element.click();}\n catch(e) {\n var evt = document.createEvent(\"MouseEvents\");\n evt.initMouseEvent(\"click\",true,true,window,0,0,0,0,0,false,false,false,false,0,null);\n element.dispatchEvent(evt);\n }\n }\n };\n</script>\n\n<input type=\"button\" value=\"upload\" onclick=\"click(document.getElementById('inputFile'));\"><input type=\"file\" id=\"inputFile\" style=\"display:none\">\n"
},
{
"answer_id": 22146076,
"author": "joan16v",
"author_id": 1398876,
"author_profile": "https://Stackoverflow.com/users/1398876",
"pm_score": 1,
"selected": false,
"text": "<script>\n function sel_file() {\n $(\"input[name=userfile]\").trigger('click');\n } \n</script>\n\n<input type=\"file\" name=\"userfile\" id=\"userfile\" />\n\n<a href=\"javascript:sel_file();\">Click</a>\n"
},
{
"answer_id": 26681311,
"author": "Aidin",
"author_id": 2321594,
"author_profile": "https://Stackoverflow.com/users/2321594",
"pm_score": 2,
"selected": false,
"text": "popFileSelector = function() {\n var el = document.getElementById(\"fileElem\");\n if (el) {\n el.click(); \n }\n};\n\nwindow.popRightAway = function() {\n document.getElementById('log').innerHTML += 'I am right away!<br />';\n popFileSelector();\n};\n\nwindow.popWithDelay = function() {\n document.getElementById('log').innerHTML += 'I am gonna delay!<br />';\n window.setTimeout(function() {\n document.getElementById('log').innerHTML += 'I was delayed!<br />';\n popFileSelector();\n }, 1000);\n}; <body>\n <form>\n <input type=\"file\" id=\"fileElem\" multiple accept=\"image/*\" style=\"display:none\" onchange=\"handleFiles(this.files)\" />\n </form>\n <a onclick=\"popRightAway()\" href=\"#\">Pop Now</a>\n <br />\n <a onclick=\"popWithDelay()\" href=\"#\">Pop With 1 Second Delay</a>\n <div id=\"log\">Log: <br /></div>\n</body>"
},
{
"answer_id": 32917668,
"author": "EscapeNetscape",
"author_id": 2689455,
"author_profile": "https://Stackoverflow.com/users/2689455",
"pm_score": 1,
"selected": false,
"text": "var evObj = document.createEvent('MouseEvents');\nevObj.initMouseEvent('click', true, true, window); \nsetTimeout(function(){ document.getElementById('input_field_id').dispatchEvent(evObj); },100);\n <div onclick=\"openFileChooser()\" class=\"some_fancy_stuff\">Click here to open image chooser</div>\n<input type=\"file\" id=\"input_img\">\n function openFileChooser() {\n var evObj = document.createEvent('MouseEvents');\n evObj.initMouseEvent('click', true, true, window); \n setTimeout(function()\n { \n document.getElementById('input_img').dispatchEvent(evObj); \n },100); \n }\n"
},
{
"answer_id": 34158355,
"author": "Adam Fischer",
"author_id": 3472662,
"author_profile": "https://Stackoverflow.com/users/3472662",
"pm_score": 2,
"selected": false,
"text": "<script>\n function upload_image_init(){\n var elem = document.getElementById('file');\n if(elem && document.createEvent) {\n var evt = document.createEvent(\"MouseEvents\");\n evt.initEvent(\"click\", true, false);\n elem.dispatchEvent(evt);\n }\n }\n</script>\n"
},
{
"answer_id": 36281035,
"author": "Avanish Kumar",
"author_id": 4813631,
"author_profile": "https://Stackoverflow.com/users/4813631",
"pm_score": 0,
"selected": false,
"text": "<button id=\"file\">select file</button>\n<input type=\"file\" name=\"file\" id=\"file_input\" style=\"display:none;\">\n<script>\n$('#file').click(function() {\n $('#file_input').focus().trigger('click');\n });\n</script>\n"
},
{
"answer_id": 38139309,
"author": "Shankar Shastri",
"author_id": 4268228,
"author_profile": "https://Stackoverflow.com/users/4268228",
"pm_score": 2,
"selected": false,
"text": "$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {\n var fileName = invoiceNumberEntity + \".pdf\";\n var pdfDownload = document.createElement(\"a\");\n document.body.appendChild(pdfDownload);\n\n AngularWebService.getFileWithSuffix(\"ezbillpdfget\",invoiceNumberEntity,\"pdf\" ).then(function(returnedJSON) {\n var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});\n if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser\n window.navigator.msSaveBlob(fileBlob, fileName);\n } else { // for other browsers\n var fileURL = window.URL.createObjectURL(fileBlob);\n pdfDownload.href = fileURL;\n pdfDownload.download = fileName;\n pdfDownload.click(); \n }\n });\n};\n"
},
{
"answer_id": 68496943,
"author": "Jérôme Beau",
"author_id": 650104,
"author_profile": "https://Stackoverflow.com/users/650104",
"pm_score": 0,
"selected": false,
"text": "function simulateFileClick() {\n const div = document.createElement(\"div\")\n div.style.visibility = \"hidden\"\n div.style.position = \"absolute\"\n div.style.width = \"100%\"\n div.style.height = \"100%\"\n div.style.pointerEvents = \"none\"\n const fileInput = document.getElementById(\"fileInput\") // or whatever selector you like\n fileInput.style.position = \"relative\"\n fileInput.appendChild(div)\n const mouseEvent = new MouseEvent(\"click\")\n div.dispatchEvent(mouseEvent)\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28655/"
] |
210,645
|
<p>I'm currently creating a website for a client that will basically involve selling various files. This is obviously a really common thing to do, which is making me feel kind of foolish for not thinking of a method for doing it.</p>
<p>Once the purchase has been made the customer should be taken to a page containing the download link, as well as receiving emails that contain a download link and an email with information about an account that will be created for them (they will also be able to download from their account's control panel). What I'm trying to figure out is how I can hide/obscure the file's location on my server so that one person who buys it can't simply copy and paste the direct link to the file elsewhere. Even if I make the request to download a file a link of the format <a href="http://example.com/blah/download/454643" rel="nofollow noreferrer">http://example.com/blah/download/454643</a>, a URL which does not correspond to the actual location of the file, I think it might still be possible to locate the file on the server? I don't really understand too much about how permissions work on my server, which is why I ask. Thanks in advance :)</p>
|
[
{
"answer_id": 210672,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 1,
"selected": false,
"text": "// Now send the file with header() magic\n header(\"Expires: Mon, 26 Nov 1962 00:00:00 GMT\");\n header(\"Last-Modified: \" . gmdate(\"D,d M Y H:i:s\") . \" GMT\");\n header(\"Cache-Control: no-cache, must-revalidate\");\n header(\"Pragma: no-cache\");\n header(\"Content-Type: Application/octet-stream\");\n header(\"Content-disposition: attachment; filename=\" . $downloads['orders_products_filename']);\n\n if (DOWNLOAD_BY_REDIRECT == 'true') {\n// This will work only on Unix/Linux hosts\n tep_unlink_temp_dir(DIR_FS_DOWNLOAD_PUBLIC);\n $tempdir = tep_random_name();\n umask(0000);\n mkdir(DIR_FS_DOWNLOAD_PUBLIC . $tempdir, 0777);\n symlink(DIR_FS_DOWNLOAD . $downloads['orders_products_filename'], DIR_FS_DOWNLOAD_PUBLIC . $tempdir . '/' . $downloads['orders_products_filename']);\n if (file_exists(DIR_FS_DOWNLOAD_PUBLIC . $tempdir . '/' . $downloads['orders_products_filename'])) {\n tep_redirect(tep_href_link(DIR_WS_DOWNLOAD_PUBLIC . $tempdir . '/' . $downloads['orders_products_filename']));\n }\n }\n"
},
{
"answer_id": 210904,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "// $mimeType is the mime type of the file\nheader('Content-type: ' . $mimeType);\n// this will get the size of the file\n// (helps for giving the size to the browser so a percent complete can be shown)\nheader('Content-length: ' . (string) (filesize($path)));\n// disposition is either attachment (for binary files that can't be read by the browser) \n// or inline (for files that can be read by the browser\n// some times you have play with this to get working so users get the download window in all browsers\n// original filename is the name you want to users to see \n// (shouldn't have any special characters as you can end up with weird issues)\nheader('Content-Disposition: ' . $disposition . '; filename=' . $originalFilename);\n// the next 2 lines try to help the browser understand that the file can't be cached\n// and should be downloaded (not viewed)\nheader('Pragma: Public');\nheader('Cache-control: private');\n// this will output the file to browser\nreadfile($path);\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12765/"
] |
210,646
|
<p>I'm trying to determine how I can detect when the user changes the Windows Font Size from Normal to Extra Large Fonts, the font size is selected by executing the following steps on a Windows XP machine:</p>
<ol>
<li>Right-click on the desktop and select Properties.</li>
<li>Click on the Appearance Tab.</li>
<li>Select the Font Size: Normal/Large Fonts/Extra Large Fonts</li>
</ol>
<p>My understanding is that the font size change results in a DPI change, so here is what I've tried so far.</p>
<hr>
<h2>My Goal:</h2>
<p>I want to detect when the <strong>Windows Font Size</strong> has changed from Normal to Large or Extra Large Fonts and take some actions based on that font size change. I assume that when the Windows Font Size changes, the DPI will also change (especially when the size is Extra Large Fonts</p>
<hr>
<h2>What I've tried so far:</h2>
<p>I receive several messages including: WM_SETTINGCHANGE, WM_NCCALCSIZE, WM_NCPAINT, etc... but none of these messages are unique to the situation when the font size changes, in other words, when I receive the WM_SETTINGSCHANGE message I want to know what changed.</p>
<p>In theory when I define the OnSettingChange and Windows calls it, the lpszSection should tell me what the changing section is, and that works fine, but then I check the given section by calling SystemParametersInfo and I pass in the action SPI_GETNONCLIENTMETRICS, and I step through the debugger and I make sure that I watch the data in the returned NONCLIENTMETRICS for any font changes, but none occur.</p>
<p>Even if that didn't work, I should still be able to check the DPI when the Settings change. I really wouldn't care about the other details, every time I get the WM_SETTINGCHANGE message, I would just check the DPI and perform the actions I'm interested in performing, but I'm not able to get the system DPI either.</p>
<p>I have tried to get the DPI by invoking the method GetSystemMetrics, also for each DC:</p>
<p>Dekstop DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Window DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Current DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY</p>
<p>Even if I change the DPI in the Graphic Properties Window these values don't return anything different, they always show 96.</p>
<p>Could anybody help me figure this out please? What should I be looking for? Where should I be looking at?</p>
<pre><code>afx_msg void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
int windowDPI = 0;
int deviceDPI = 0;
int systemDPI = 0;
int desktopDPI = 0;
int dpi_00_X = 0;
int dpi_01_X = 0;
int dpi_02_X = 0;
int dpi_03_X = 0;
CDC* windowDC = CWnd::GetWindowDC(); // try with window DC
HDC desktop = ::GetDC(NULL); // try with desktop DC
CDC* device = CWnd::GetDC(); // try with current DC
HDC hDC = *device; // try with HDC
if( windowDC )
{
windowDPI = windowDC->GetDeviceCaps(LOGPIXELSY);
// always 96 regardless if I change the Font
// Size to Extra Large Fonts or keep it at Normal
dpi_00_X = windowDC->GetDeviceCaps(LOGPIXELSX); // 96
}
if( desktop )
{
desktopDPI = ::GetDeviceCaps(desktop, LOGPIXELSY); // 96
dpi_01_X = ::GetDeviceCaps(desktop, LOGPIXELSX); // 96
}
if( device )
{
deviceDPI = device->GetDeviceCaps(LOGPIXELSY); // 96
dpi_02_X = device->GetDeviceCaps(LOGPIXELSX); // 96
}
systemDPI = ::GetDeviceCaps(hDC, LOGPIXELSY); // 96
dpi_03_X = ::GetDeviceCaps(hDC, LOGPIXELSX); // 96
CWnd::ReleaseDC(device);
CWnd::ReleaseDC(windowDC);
::ReleaseDC(NULL, desktop);
::ReleaseDC(NULL, hDC);
CWnd::OnWinSettingChange(uFlags, lpszSection);
}
</code></pre>
<p>The DPI always returns 96, but the settings changes DO take effect when I change the font size to Extra Large Fonts or if I change the DPI to 120 (from the graphics properties).</p>
|
[
{
"answer_id": 211790,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 2,
"selected": false,
"text": "int GetScreenDPI()\n{\n HDC hdcScreen = ::GetDC(NULL);\n int iDPI = -1; // assume failure\n if (hdcScreen) {\n iDPI = ::GetDeviceCaps(hdcScreen, LOGPIXELSX);\n ::ReleaseDC(NULL, hdcScreen);\n }\n return iDPI;\n}\n"
},
{
"answer_id": 213373,
"author": "jeffm",
"author_id": 1544,
"author_profile": "https://Stackoverflow.com/users/1544",
"pm_score": 0,
"selected": false,
"text": "WM_PAINT WM_NCPAINT"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28760/"
] |
210,650
|
<p>I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.</p>
<pre><code>string filePath = "image.jpg";
Image newImage = Image.FromFile(filePath);
</code></pre>
<p>The problem occurs when image.jpg isn't really a jpg. For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception will be thrown when image.jpg is loaded.</p>
<p>I'm looking for a function that will validate an image given a stream or a file path of the image.</p>
<p>Example function prototype</p>
<pre><code>bool IsValidImage(string fileName);
bool IsValidImage(Stream imageStream);
</code></pre>
|
[
{
"answer_id": 210660,
"author": "Enrico Murru",
"author_id": 68336,
"author_profile": "https://Stackoverflow.com/users/68336",
"pm_score": 0,
"selected": false,
"text": "Image openImage(string filename);\n"
},
{
"answer_id": 210671,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 5,
"selected": false,
"text": "bool IsValidImage(string filename)\n{\n try\n {\n using(Image newImage = Image.FromFile(filename))\n {}\n }\n catch (OutOfMemoryException ex)\n {\n //The file does not have a valid image format.\n //-or- GDI+ does not support the pixel format of the file\n\n return false;\n }\n return true;\n}\n bool IsValidImage(string filename)\n{\n try\n {\n using(BitmapImage newImage = new BitmapImage(filename))\n {}\n }\n catch(NotSupportedException)\n {\n // System.NotSupportedException:\n // No imaging component suitable to complete this operation was found.\n return false;\n }\n return true;\n}\n"
},
{
"answer_id": 211154,
"author": "SemiColon",
"author_id": 1994,
"author_profile": "https://Stackoverflow.com/users/1994",
"pm_score": 4,
"selected": false,
"text": "static bool IsValidImage(string filePath)\n{\n return File.Exists(filePath) && IsValidImage(new FileStream(filePath, FileMode.Open, FileAccess.Read));\n}\n\nstatic bool IsValidImage(Stream imageStream)\n{\n if(imageStream.Length > 0)\n {\n byte[] header = new byte[4]; // Change size if needed.\n string[] imageHeaders = new[]{\n \"\\xFF\\xD8\", // JPEG\n \"BM\", // BMP\n \"GIF\", // GIF\n Encoding.ASCII.GetString(new byte[]{137, 80, 78, 71})}; // PNG\n\n imageStream.Read(header, 0, header.Length);\n\n bool isImageHeader = imageHeaders.Count(str => Encoding.ASCII.GetString(header).StartsWith(str)) > 0;\n if (isImageHeader == true)\n {\n try\n {\n Image.FromStream(imageStream).Dispose();\n imageStream.Close();\n return true;\n }\n\n catch\n {\n\n }\n }\n }\n\n imageStream.Close();\n return false;\n}\n"
},
{
"answer_id": 2063677,
"author": "lorddarq",
"author_id": 250672,
"author_profile": "https://Stackoverflow.com/users/250672",
"pm_score": -1,
"selected": false,
"text": "Image.FromStream"
},
{
"answer_id": 2425028,
"author": "Paulo",
"author_id": 157693,
"author_profile": "https://Stackoverflow.com/users/157693",
"pm_score": 2,
"selected": false,
"text": "private bool IsValidImage(string filename)\n{\n Stream imageStream = null;\n try\n {\n imageStream = new FileStream(filename, FileMode.Open);\n\n if (imageStream.Length > 0)\n {\n byte[] header = new byte[30]; // Change size if needed.\n string[] imageHeaders = new[]\n {\n \"BM\", // BMP\n \"GIF\", // GIF\n Encoding.ASCII.GetString(new byte[]{137, 80, 78, 71}),// PNG\n \"MM\\x00\\x2a\", // TIFF\n \"II\\x2a\\x00\" // TIFF\n };\n\n imageStream.Read(header, 0, header.Length);\n\n bool isImageHeader = imageHeaders.Count(str => Encoding.ASCII.GetString(header).StartsWith(str)) > 0;\n if (imageStream != null)\n {\n imageStream.Close();\n imageStream.Dispose();\n imageStream = null;\n }\n\n if (isImageHeader == false)\n {\n //Verify if is jpeg\n using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))\n {\n UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8)\n UInt16 jfif = br.ReadUInt16(); // JFIF marker\n\n return soi == 0xd8ff && (jfif == 0xe0ff || jfif == 57855);\n }\n }\n\n return isImageHeader;\n }\n\n return false;\n }\n catch { return false; }\n finally\n {\n if (imageStream != null)\n {\n imageStream.Close();\n imageStream.Dispose();\n }\n }\n}\n"
},
{
"answer_id": 3144215,
"author": "David Boike",
"author_id": 10039,
"author_profile": "https://Stackoverflow.com/users/10039",
"pm_score": 3,
"selected": false,
"text": "using(Image test = Image.FromFile(filePath))\n{\n bool isJpeg = (test.RawFormat.Equals(ImageFormat.Jpeg));\n}\n"
},
{
"answer_id": 9215864,
"author": "ray",
"author_id": 250385,
"author_profile": "https://Stackoverflow.com/users/250385",
"pm_score": 1,
"selected": false,
"text": "Private Function IsValidImage(imageStream As System.IO.Stream) As Boolean\n\n If (imageStream.Length = 0) Then\n isvalidimage = False\n Exit Function\n End If\n\n Dim pngByte() As Byte = New Byte() {137, 80, 78, 71}\n Dim pngHeader As String = System.Text.Encoding.ASCII.GetString(pngByte)\n\n Dim jpgByte() As Byte = New Byte() {255, 216}\n Dim jpgHeader As String = System.Text.Encoding.ASCII.GetString(jpgByte)\n\n Dim bmpHeader As String = \"BM\"\n Dim gifHeader As String = \"GIF\"\n\n Dim header(3) As Byte\n\n Dim imageHeaders As String() = New String() {jpgHeader, bmpHeader, gifHeader, pngHeader}\n imageStream.Read(header, 0, header.Length)\n\n Dim isImageHeader As Boolean = imageHeaders.Count(Function(str) System.Text.Encoding.ASCII.GetString(header).StartsWith(str)) > 0\n\n If (isImageHeader) Then\n Try\n System.Drawing.Image.FromStream(imageStream).Dispose()\n imageStream.Close()\n IsValidImage = True\n Exit Function\n Catch ex As Exception\n System.Diagnostics.Debug.WriteLine(\"Not an image\")\n End Try\n Else\n System.Diagnostics.Debug.WriteLine(\"Not an image\")\n End If\n\n imageStream.Close()\n IsValidImage = False\n End Function\n"
},
{
"answer_id": 9446045,
"author": "Alex",
"author_id": 499558,
"author_profile": "https://Stackoverflow.com/users/499558",
"pm_score": 6,
"selected": false,
"text": "public enum ImageFormat\n{\n bmp,\n jpeg,\n gif,\n tiff,\n png,\n unknown\n}\n\npublic static ImageFormat GetImageFormat(byte[] bytes)\n{\n // see http://www.mikekunz.com/image_file_header.html \n var bmp = Encoding.ASCII.GetBytes(\"BM\"); // BMP\n var gif = Encoding.ASCII.GetBytes(\"GIF\"); // GIF\n var png = new byte[] { 137, 80, 78, 71 }; // PNG\n var tiff = new byte[] { 73, 73, 42 }; // TIFF\n var tiff2 = new byte[] { 77, 77, 42 }; // TIFF\n var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg\n var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon\n\n if (bmp.SequenceEqual(bytes.Take(bmp.Length)))\n return ImageFormat.bmp;\n\n if (gif.SequenceEqual(bytes.Take(gif.Length)))\n return ImageFormat.gif;\n\n if (png.SequenceEqual(bytes.Take(png.Length)))\n return ImageFormat.png;\n\n if (tiff.SequenceEqual(bytes.Take(tiff.Length)))\n return ImageFormat.tiff;\n\n if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))\n return ImageFormat.tiff;\n\n if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))\n return ImageFormat.jpeg;\n\n if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))\n return ImageFormat.jpeg;\n\n return ImageFormat.unknown;\n}\n"
},
{
"answer_id": 34087446,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 2,
"selected": false,
"text": "try {\n using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n {\n Image im = Image.FromStream(stream);\n // Do something with image if needed.\n }\n}\ncatch (ArgumentException)\n{\n if( !IsValidImageFormat(path) )\n return SetLastError(\"File '\" + fileName + \"' is not a valid image\");\n\n throw;\n}\n /// <summary>\n/// Check if we have valid Image file format.\n/// </summary>\n/// <param name=\"path\"></param>\n/// <returns>true if it's image file</returns>\npublic static bool IsValidImageFormat( String path )\n{\n using ( FileStream fs = File.OpenRead(path) )\n {\n byte[] header = new byte[10];\n fs.Read(header, 0, 10);\n\n foreach ( var pattern in new byte[][] {\n Encoding.ASCII.GetBytes(\"BM\"),\n Encoding.ASCII.GetBytes(\"GIF\"),\n new byte[] { 137, 80, 78, 71 }, // PNG\n new byte[] { 73, 73, 42 }, // TIFF\n new byte[] { 77, 77, 42 }, // TIFF\n new byte[] { 255, 216, 255, 224 }, // jpeg\n new byte[] { 255, 216, 255, 225 } // jpeg canon\n } )\n {\n if (pattern.SequenceEqual(header.Take(pattern.Length)))\n return true;\n }\n }\n\n return false;\n} //IsValidImageFormat\n"
},
{
"answer_id": 59467826,
"author": "Shadam",
"author_id": 2610693,
"author_profile": "https://Stackoverflow.com/users/2610693",
"pm_score": 3,
"selected": false,
"text": "public static bool IsImage(this byte[] fileBytes)\n{\n var headers = new List<byte[]>\n {\n Encoding.ASCII.GetBytes(\"BM\"), // BMP\n Encoding.ASCII.GetBytes(\"GIF\"), // GIF\n new byte[] { 137, 80, 78, 71 }, // PNG\n new byte[] { 73, 73, 42 }, // TIFF\n new byte[] { 77, 77, 42 }, // TIFF\n new byte[] { 255, 216, 255, 224 }, // JPEG\n new byte[] { 255, 216, 255, 225 } // JPEG CANON\n };\n\n return headers.Any(x => x.SequenceEqual(fileBytes.Take(x.Length)));\n}\n public async Task UploadImage(Stream file)\n{\n using (MemoryStream ms = new MemoryStream())\n {\n await file.CopyToAsync(ms);\n\n byte[] bytes = ms.ToArray();\n\n if (!bytes.IsImage())\n throw new ArgumentException(\"Not an image\", nameof(file));\n\n // Upload your file\n }\n}\n"
},
{
"answer_id": 60132323,
"author": "XzaR",
"author_id": 3153684,
"author_profile": "https://Stackoverflow.com/users/3153684",
"pm_score": 0,
"selected": false,
"text": "public class ImageValidator\n{\n private readonly Dictionary<string,byte[]> _validBytes = new Dictionary<string, byte[]>() {\n { \".bmp\", new byte[] { 66, 77 } },\n { \".gif\", new byte[] { 71, 73, 70, 56 } },\n { \".ico\", new byte[] { 0, 0, 1, 0 } },\n { \".jpg\", new byte[] { 255, 216, 255 } },\n { \".png\", new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 } },\n { \".tiff\", new byte[] { 73, 73, 42, 0 } },\n };\n\n /// <summary>\n /// image formats to validate using Guids from ImageFormat.\n /// </summary>\n private readonly Dictionary<Guid, string> _validGuids = new Dictionary<Guid, string>() {\n {ImageFormat.Jpeg.Guid, \".jpg\" },\n {ImageFormat.Png.Guid, \".png\"},\n {ImageFormat.Bmp.Guid, \".bmp\"},\n {ImageFormat.Gif.Guid, \".gif\"},\n {ImageFormat.Tiff.Guid, \".tiff\"},\n {ImageFormat.Icon.Guid, \".ico\" }\n };\n\n /// <summary>\n /// Supported extensions: .jpg,.png,.bmp,.gif,.tiff,.ico\n /// </summary>\n /// <param name=\"allowedExtensions\"></param>\n public ImageValidator(string allowedExtensions = \".jpg;.png\")\n {\n var exts = allowedExtensions.Split(';');\n foreach (var pair in _validGuids.ToArray())\n {\n if (!exts.Contains(pair.Value))\n {\n _validGuids.Remove(pair.Key);\n }\n }\n\n foreach (var pair in _validBytes.ToArray())\n {\n if (!exts.Contains(pair.Key))\n {\n _validBytes.Remove(pair.Key);\n }\n }\n }\n\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Style\", \"IDE0063:Use simple 'using' statement\", Justification = \"<Pending>\")]\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Design\", \"CA1031:Do not catch general exception types\", Justification = \"<Pending>\")]\n public async Task<bool> IsValidAsync(Stream imageStream, string filePath)\n {\n if(imageStream == null || imageStream.Length == 0)\n {\n return false;\n }\n\n //First validate using file extension\n string ext = Path.GetExtension(filePath).ToLower();\n if(!_validGuids.ContainsValue(ext))\n {\n return false;\n }\n\n //Check mimetype by content\n if(!await IsImageBySigAsync(imageStream, ext))\n {\n return false;\n }\n\n try\n {\n //Validate file using Guid.\n using (var image = Image.FromStream(imageStream))\n {\n imageStream.Position = 0;\n var imgGuid = image.RawFormat.Guid;\n if (!_validGuids.ContainsKey(imgGuid))\n {\n return false;\n }\n\n var validExtension = _validGuids[imgGuid];\n if (validExtension != ext)\n {\n return false;\n }\n }\n }\n catch (OutOfMemoryException)\n {\n return false;\n }\n\n return true;\n }\n\n /// <summary>\n /// Validate the mimetype using byte and file extension.\n /// </summary>\n /// <param name=\"imageStream\"></param>\n /// <param name=\"extension\"></param>\n /// <returns></returns>\n private async Task<bool> IsImageBySigAsync(Stream imageStream, string extension)\n {\n var length = _validBytes.Max(x => x.Value.Length);\n byte[] imgByte = new byte[length];\n await imageStream.ReadAsync(imgByte, 0, length);\n imageStream.Position = 0;\n\n if (_validBytes.ContainsKey(extension))\n {\n var validImgByte = _validBytes[extension];\n if (imgByte.Take(validImgByte.Length).SequenceEqual(validImgByte))\n {\n return true;\n }\n }\n\n return false;\n }\n}\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1994/"
] |
210,657
|
<p>I've defined an error-page in my web.xml:</p>
<pre><code> <error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</code></pre>
<p>In that error page, I have a custom tag that I created. The tag handler for this tag e-mails me the stacktrace of whatever error occurred. For the most part this works great.</p>
<p>Where it doesn't work great is if the output has already begun being sent to the client at the time the error occurs. In that case, we get this:</p>
<pre><code>SEVERE: Exception Processing ErrorPage[exceptionType=java.lang.Exception, location=/error.jsp]
java.lang.IllegalStateException
</code></pre>
<p>I believe this error happens because we can't redirect a request to the error page after output has already started. The work-around I've used is to increase the buffer size on particularly large JSP pages. But I'm trying to write a generic error handler that I can apply to existing applications, and I'm not sure it's feasible to go through hundreds of JSP pages making sure their buffers are big enough.</p>
<p>Is there a way to still allow my stack trace e-mail code to execute in this case, even if I can't actually display the error page to the client?</p>
|
[
{
"answer_id": 1833962,
"author": "David Smiley",
"author_id": 92186,
"author_profile": "https://Stackoverflow.com/users/92186",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\n var pageLoadSuccessful = false;//set to true in footer.jsp\n dojo.addOnLoad(function(){\n if (!pageLoadSuccessful) window.location = \"<c:url value=\"/error.do\" />\";\n });\n</script>\n <script type=\"text/javascript\">\n pageLoadSuccessful = true;//declared in header.jsp\n</script>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] |
210,666
|
<p>I have a CircleButton class in Actionscript.
I want to know when someone externally has changed the 'on' property.
I try listening to 'onChange' but it never hits that event handler.</p>
<p>I know I can write the 'on' property as a get/setter but I like the simplicity of just using [Bindable]</p>
<p>Can an object not listen to its own events?</p>
<pre><code>public class CircleButton extends UIComponent
{
[Bindable]
public var on:Boolean;
public function CircleButton()
{
this.width = 20;
this.height = 20;
graphics.beginFill(0xff6600, 1);
graphics.drawCircle(width/2, height/2, width/2);
graphics.endFill();
this.addEventListener(MouseEvent.ROLL_OVER, rollover);
this.addEventListener(MouseEvent.ROLL_OUT, rollout);
this.addEventListener('onChange', onOnChange);
}
private function onOnChange(event:PropertyChangeEvent):void {
</code></pre>
|
[
{
"answer_id": 215440,
"author": "Laura",
"author_id": 5103,
"author_profile": "https://Stackoverflow.com/users/5103",
"pm_score": 4,
"selected": true,
"text": "this.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onOnChange);\n [Bindable(event=\"myOnChangeEvent\")]\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24727/"
] |
210,682
|
<p>our partners sites leverages our iframes in their own websites. I was wondering if there is a way to track the analytics on the iframes. </p>
<p>The problem is, if we also utilize these iframes on our own website, how do i avoid duplicate tracking where a visit is counted on our domain's analytics and also counted again in iframes? is there a way to get around it?</p>
|
[
{
"answer_id": 210704,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 2,
"selected": false,
"text": "if ( location.href.indexOf(\"utm_source=mysite\") < 0 )\n{\n // Google Analytics code here\n}\n"
},
{
"answer_id": 3381289,
"author": "Avishai",
"author_id": 76735,
"author_profile": "https://Stackoverflow.com/users/76735",
"pm_score": 0,
"selected": false,
"text": "utm_nooverride=1 <iframe src=\"mypage.html?utm_nooverride=1\" width=\"1\" height=\"1\"></iframe>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,692
|
<p>We have a proprietry system that we develop scripting code in.
We currently do not have a developer environment (apart from Notepad++) and cannot debug or compile this code. We have to submit it to the vendor to insert the code into the test or live system.
The language is essentially C like and has the same syntax.
Basically we want a tool to be able to simply check the syntax of chunks of code we send to the vendor.
Does a tool exist that will do this for me?</p>
|
[
{
"answer_id": 210701,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "/Zs"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,711
|
<p>In ASP.NET MVC is there an equivalent of the Html.ActionLink helper for Img tags? </p>
<p>I have a controller action that outputs a dynamically generated JPEG and I wanted to use the same Lambda expressions to link to it as I do HREFs using ActionLink.</p>
<p>Alternatively, a helper that just gives the URL to a route (again specified using Lambdas) would also be acceptable. </p>
<p><strong>EDIT</strong>: I had originally specified that I was using Preview 5, however I see that a Beta has been released. So all-in-all the version number was an unneeded piece of info as I may be upgrading soon :-)</p>
|
[
{
"answer_id": 309413,
"author": "adamjcooper",
"author_id": 27867,
"author_profile": "https://Stackoverflow.com/users/27867",
"pm_score": 2,
"selected": false,
"text": "<a href=\"<%=Html.BuildUrlFromExpression<MyController>(c => c.MyAction())%>\">\n <%=Html.Image(\"~/Content/MyImage.gif\")%>\n</a>\n img\n{\n border: none;\n}\n"
},
{
"answer_id": 394864,
"author": "Alan Mendelevich",
"author_id": 19546,
"author_profile": "https://Stackoverflow.com/users/19546",
"pm_score": 3,
"selected": false,
"text": "<%= Html.ActionLink(\"__IMAGE_PLACEHOLDER__\", \"Products\").Replace(\"__IMAGE_PLACEHOLDER__\", \"<img src=\\\"\" + myImgUrl + \"\\\" />\")%>\n"
},
{
"answer_id": 566065,
"author": "realMarkusSchmidt",
"author_id": 60576,
"author_profile": "https://Stackoverflow.com/users/60576",
"pm_score": 5,
"selected": false,
"text": "<a href=\"<%= Url.RouteUrl(\"MyRoute\", new { param1 = \"bla\", param2 = 5 }) %>\">\n put in <span>whatever</span> you want, also <img src=\"a.gif\" alt=\"images\" />.\n</a>\n"
},
{
"answer_id": 1172632,
"author": "Robert MacLean",
"author_id": 53236,
"author_profile": "https://Stackoverflow.com/users/53236",
"pm_score": 6,
"selected": false,
"text": "<a href=\"<%= Url.Action(\"Create\") %>\"><img src=\"../../Content/Images/add_48.png\" /></a>\n"
},
{
"answer_id": 2778678,
"author": "Maksymilian Majer",
"author_id": 310274,
"author_profile": "https://Stackoverflow.com/users/310274",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Linq.Expressions;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nusing ExpressionHelperInternal=Microsoft.Web.Mvc.Internal.ExpressionHelper;\n\nnamespace Bnv.Bssi.Web.Infrastructure.Helpers\n{\n public static class UrlExtensions\n {\n public static string Action<TController>(this UrlHelper helper, Expression<Action<TController>> action) where TController : Controller\n {\n RouteValueDictionary routeValuesFromExpression = ExpressionHelperInternal.GetRouteValuesFromExpression<TController>(action);\n\n return helper.Action(routeValuesFromExpression[\"action\"].ToString(), routeValuesFromExpression);\n }\n }\n}\n <img src=\"<%= Url.Action<YourController>(c => c.YourActionMethod(param1, param2)); %>\" />\n"
},
{
"answer_id": 4634029,
"author": "tivo",
"author_id": 222761,
"author_profile": "https://Stackoverflow.com/users/222761",
"pm_score": 0,
"selected": false,
"text": "@(new HtmlString(Html.ActionLink(Html.Image(\"image.gif\").ToString(), \"myAction\", \"MyController\").ToString().Replace(\"<\", \"<\").Replace(\">\", \">\")))\n"
},
{
"answer_id": 5783059,
"author": "WEFX",
"author_id": 590719,
"author_profile": "https://Stackoverflow.com/users/590719",
"pm_score": 3,
"selected": false,
"text": "<a href=\"@Url.Action(\"Create\")\"><img src=\"../../Content/Images/add_48.png\" /></a>\n"
},
{
"answer_id": 8145801,
"author": "Wahid Bitar",
"author_id": 105445,
"author_profile": "https://Stackoverflow.com/users/105445",
"pm_score": 2,
"selected": false,
"text": "public static class ImageExtensions\n{\n public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string additionalText = null, string actionName = null, string controllerName = null, object routeValues = null, object linkHtmlAttributes = null, object imgHtmlAttributes = null)\n {\n var urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;\n var url = \"#\";\n if (!string.IsNullOrEmpty(actionName))\n url = urlHelper.Action(actionName, controllerName, routeValues);\n\n var imglink = new TagBuilder(\"a\");\n imglink.MergeAttribute(\"href\", url);\n imglink.InnerHtml = htmlHelper.Image(imgSrc, imgHtmlAttributes) + \" \" + additionalText;\n linkHtmlAttributes = new RouteValueDictionary(linkHtmlAttributes);\n imglink.MergeAttributes((IDictionary<string, object>)linkHtmlAttributes, true);\n\n return MvcHtmlString.Create(imglink.ToString());\n }\n\n public static MvcHtmlString Image(this HtmlHelper htmlHelper, string imgSrc, object imgHtmlAttributes = null)\n {\n var imgTag = new TagBuilder(\"img\");\n imgTag.MergeAttribute(\"src\", imgSrc);\n if (imgHtmlAttributes != null)\n {\n imgHtmlAttributes = new RouteValueDictionary(imgHtmlAttributes);\n imgTag.MergeAttributes((IDictionary<string, object>)imgHtmlAttributes, true);\n }\n return MvcHtmlString.Create(imgTag.ToString());\n }\n}\n"
},
{
"answer_id": 11394714,
"author": "Jon",
"author_id": 6486,
"author_profile": "https://Stackoverflow.com/users/6486",
"pm_score": 1,
"selected": false,
"text": " public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName)\n {\n return ActionImageLink(helper, src, altText, url, actionName, controllerName, null, null);\n }\n\n public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName, Dictionary<string, string> linkAttributes, Dictionary<string, string> imageAttributes)\n {\n return ActionImageLink(helper, src, altText, url, actionName, controllerName, null, linkAttributes, imageAttributes);\n }\n\n public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName, dynamic routeValues, Dictionary<string, string> linkAttributes, Dictionary<string, string> imageAttributes)\n {\n var linkBuilder = new TagBuilder(\"a\");\n linkBuilder.MergeAttribute(\"href\", routeValues == null ? url.Action(actionName, controllerName) : url.Action(actionName, controllerName, routeValues));\n\n var imageBuilder = new TagBuilder(\"img\");\n imageBuilder.MergeAttribute(\"src\", url.Content(src));\n imageBuilder.MergeAttribute(\"alt\", altText);\n\n if (linkAttributes != null)\n {\n foreach (KeyValuePair<string, string> attribute in linkAttributes)\n {\n if (!string.IsNullOrWhiteSpace(attribute.Key) && !string.IsNullOrWhiteSpace(attribute.Value))\n {\n linkBuilder.MergeAttribute(attribute.Key, attribute.Value);\n }\n }\n }\n\n if (imageAttributes != null)\n {\n foreach (KeyValuePair<string, string> attribute in imageAttributes)\n {\n if (!string.IsNullOrWhiteSpace(attribute.Key) && !string.IsNullOrWhiteSpace(attribute.Value))\n {\n imageBuilder.MergeAttribute(attribute.Key, attribute.Value);\n }\n }\n }\n\n linkBuilder.InnerHtml = MvcHtmlString.Create(imageBuilder.ToString(TagRenderMode.SelfClosing)).ToString();\n return MvcHtmlString.Create(linkBuilder.ToString());\n }\n"
},
{
"answer_id": 11521216,
"author": "Ando",
"author_id": 209407,
"author_profile": "https://Stackoverflow.com/users/209407",
"pm_score": 0,
"selected": false,
"text": " public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string cultureName, object htmlAttributes, object imgHtmlAttributes, string languageRouteName = \"lang\", bool strictSelected = false)\n {\n UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;\n TagBuilder imgTag = new TagBuilder(\"img\");\n imgTag.MergeAttribute(\"src\", imgSrc);\n imgTag.MergeAttributes((IDictionary<string, string>)imgHtmlAttributes, true);\n\n var language = htmlHelper.LanguageUrl(cultureName, languageRouteName, strictSelected); \n string url = language.Url;\n\n TagBuilder imglink = new TagBuilder(\"a\");\n imglink.MergeAttribute(\"href\", url);\n imglink.InnerHtml = imgTag.ToString();\n imglink.MergeAttributes((IDictionary<string, string>)htmlAttributes, true);\n\n //if the current page already contains the language parameter make sure the corresponding html element is marked\n string currentLanguage = htmlHelper.ViewContext.RouteData.GetRequiredString(\"lang\");\n if (cultureName.Equals(currentLanguage, StringComparison.InvariantCultureIgnoreCase))\n {\n imglink.AddCssClass(\"selectedLanguage\");\n }\n return new MvcHtmlString(imglink.ToString());\n }\n"
},
{
"answer_id": 19302561,
"author": "Jeroen Visscher",
"author_id": 961139,
"author_profile": "https://Stackoverflow.com/users/961139",
"pm_score": 0,
"selected": false,
"text": " @using (Html.BeginForm(\"Action\", \"Controler\", ajaxOptions))\n { \n <button type=\"submit\">\n <img src=\"image.png\" /> \n </button>\n }\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27860/"
] |
210,717
|
<p>How do I go about setting a <code><div></code> in the center of the screen using jQuery?</p>
|
[
{
"answer_id": 210733,
"author": "Tony L.",
"author_id": 21905,
"author_profile": "https://Stackoverflow.com/users/21905",
"pm_score": 11,
"selected": true,
"text": "jQuery.fn.center = function () {\n this.css(\"position\",\"absolute\");\n this.css(\"top\", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + \n $(window).scrollTop()) + \"px\");\n this.css(\"left\", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + \n $(window).scrollLeft()) + \"px\");\n return this;\n}\n $(element).center();\n"
},
{
"answer_id": 211023,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "var myElement = $('#myElement');\nmyElement.css({\n position: 'absolute',\n left: '50%',\n 'margin-left': 0 - (myElement.width() / 2)\n});\n"
},
{
"answer_id": 2257651,
"author": "molokoloco",
"author_id": 174449,
"author_profile": "https://Stackoverflow.com/users/174449",
"pm_score": 7,
"selected": false,
"text": "$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});\n (function($){\n $.fn.extend({\n center: function () {\n return this.each(function() {\n var top = ($(window).height() - $(this).outerHeight()) / 2;\n var left = ($(window).width() - $(this).outerWidth()) / 2;\n $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});\n });\n }\n }); \n})(jQuery);\n $('#mainDiv').center();\n (function($){\n $.fn.extend({\n center: function (options) {\n var options = $.extend({ // Default values\n inside:window, // element, center into window\n transition: 0, // millisecond, transition time\n minX:0, // pixel, minimum left element value\n minY:0, // pixel, minimum top element value\n withScrolling:true, // booleen, take care of the scrollbar (scrollTop)\n vertical:true, // booleen, center vertical\n horizontal:true // booleen, center horizontal\n }, options);\n return this.each(function() {\n var props = {position:'absolute'};\n if (options.vertical) {\n var top = ($(options.inside).height() - $(this).outerHeight()) / 2;\n if (options.withScrolling) top += $(options.inside).scrollTop() || 0;\n top = (top > options.minY ? top : options.minY);\n $.extend(props, {top: top+'px'});\n }\n if (options.horizontal) {\n var left = ($(options.inside).width() - $(this).outerWidth()) / 2;\n if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;\n left = (left > options.minX ? left : options.minX);\n $.extend(props, {left: left+'px'});\n }\n if (options.transition > 0) $(this).animate(props, options.transition);\n else $(this).css(props);\n return $(this);\n });\n }\n });\n})(jQuery);\n $(document).ready(function(){\n $('#mainDiv').center();\n $(window).bind('resize', function() {\n $('#mainDiv').center({transition:300});\n });\n);\n .center {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%); /* Yep! */\n width: 48%;\n height: 59%;\n}\n"
},
{
"answer_id": 2552902,
"author": "Eric D. Fields",
"author_id": 306003,
"author_profile": "https://Stackoverflow.com/users/306003",
"pm_score": 2,
"selected": false,
"text": "// Center an element on the screen\n(function($){\n $.fn.extend({\n center: function (x,y) {\n // var options = $.extend({transition:300, minX:0, minY:0}, options);\n return this.each(function() {\n if (x == undefined) {\n x = true;\n }\n if (y == undefined) {\n y = true;\n }\n var $this = $(this);\n var $window = $(window);\n $this.css({\n position: \"absolute\",\n });\n if (x) {\n var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();\n $this.css('left',left)\n }\n if (!y == false) {\n var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop(); \n $this.css('top',top);\n }\n // $(this).animate({\n // top: (top > options.minY ? top : options.minY)+'px',\n // left: (left > options.minX ? left : options.minX)+'px'\n // }, options.transition);\n return $(this);\n });\n }\n });\n})(jQuery);\n"
},
{
"answer_id": 4408197,
"author": "cetnar",
"author_id": 104796,
"author_profile": "https://Stackoverflow.com/users/104796",
"pm_score": 6,
"selected": false,
"text": "$('your-selector').position({\n of: $(window)\n});\n"
},
{
"answer_id": 5236684,
"author": "John Butcher",
"author_id": 650320,
"author_profile": "https://Stackoverflow.com/users/650320",
"pm_score": 3,
"selected": false,
"text": "this.css(\"top\", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + \"px\");\n this.height scrollTop() = 0 window.height 600 this.height 650 600 - 650 = -50 \n\n-50 / 2 = -25\n -25"
},
{
"answer_id": 5734843,
"author": "Keith",
"author_id": 717676,
"author_profile": "https://Stackoverflow.com/users/717676",
"pm_score": 2,
"selected": false,
"text": "center: function (options, callback) {\n if (options.transition > 0) {\n $(this).animate(props, options.transition, callback);\n} else { \n $(this).css(props);\n if (typeof callback == 'function') { // make sure the callback is a function\n callback.call(this); // brings the scope to the callback\n }\n}\n"
},
{
"answer_id": 6175767,
"author": "ahmad balavipour",
"author_id": 774934,
"author_profile": "https://Stackoverflow.com/users/774934",
"pm_score": -1,
"selected": false,
"text": "#timer_wrap{ \n position: fixed;\n left: 50%;\n top: 50%;\n} \n"
},
{
"answer_id": 8959914,
"author": "Juho Vepsäläinen",
"author_id": 228885,
"author_profile": "https://Stackoverflow.com/users/228885",
"pm_score": 5,
"selected": false,
"text": "$.fn.center = function() {\n this.css({\n 'position': 'fixed',\n 'left': '50%',\n 'top': '50%'\n });\n this.css({\n 'margin-left': -this.outerWidth() / 2 + 'px',\n 'margin-top': -this.outerHeight() / 2 + 'px'\n });\n\n return this;\n}\n"
},
{
"answer_id": 9758556,
"author": "Oleg",
"author_id": 1081234,
"author_profile": "https://Stackoverflow.com/users/1081234",
"pm_score": 3,
"selected": false,
"text": ".container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}\n.helper {#position:absolute; #top:50%;\n display:table-cell; vertical-align:middle;}\n.content {#position:relative; #top:-50%;\n margin:0 auto; width:200px; border:1px solid orange;}\n .container {\n position:absolute;\n left: 50%;\n top: 50%;\n overflow:visible;\n}\n.content {\n position:relative;\n margin:-50% 50% 50% -50%;\n}\n <table class=\"super-centered\"><tr><td>\n <div class=\"content\">\n <p>I am centered like a boss!</p>\n </div>\n</td></tr></table>\n .super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}\n.content {margin:0 auto;width:200px;}\n"
},
{
"answer_id": 10275838,
"author": "Volomike",
"author_id": 105539,
"author_profile": "https://Stackoverflow.com/users/105539",
"pm_score": 4,
"selected": false,
"text": "jQuery.fn.center = function ($) {\n var w = $(window);\n this.css({\n 'position':'absolute',\n 'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),\n 'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())\n });\n return this;\n}\n jQuery(document).ready(function($){\n $('#myelem').center();\n});\n"
},
{
"answer_id": 10876317,
"author": "Andrew",
"author_id": 882371,
"author_profile": "https://Stackoverflow.com/users/882371",
"pm_score": 0,
"selected": false,
"text": "$.fn.pixels = function(property){\n return parseInt(this.css(property));\n};\n\n$.fn.center = function(){\n var w = $($w);\n return this.each(function(){\n $(this).css(\"position\",\"absolute\");\n $(this).css(\"top\",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + \"px\");\n $(this).css(\"left\",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + \"px\");\n });\n};\n"
},
{
"answer_id": 10918691,
"author": "Diego",
"author_id": 346169,
"author_profile": "https://Stackoverflow.com/users/346169",
"pm_score": 2,
"selected": false,
"text": "position: absolute fixed $.fn.center = function () {\n var heightRatio = ($(window).height() != 0) \n ? this.outerHeight() / $(window).height() : 1;\n var widthRatio = ($(window).width() != 0) \n ? this.outerWidth() / $(window).width() : 1;\n\n this.css({\n position: 'fixed',\n margin: 0,\n top: (50*(1-heightRatio)) + \"%\",\n left: (50*(1-widthRatio)) + \"%\"\n });\n\n return this;\n}\n margin: 0 .outerWidth(true) 50*(1-ratio) W = 100% w = 100 * elementWidthInPixels/windowWidthInPixels left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =\n = 50 * (1-elementWidthInPixels/windowWidthInPixels)\n"
},
{
"answer_id": 17368113,
"author": "apaul",
"author_id": 1947286,
"author_profile": "https://Stackoverflow.com/users/1947286",
"pm_score": 5,
"selected": false,
"text": ".center{\n position: absolute;\n height: 50px;\n width: 50px;\n background:red;\n top:calc(50% - 50px/2); /* height divided by 2*/\n left:calc(50% - 50px/2); /* width divided by 2*/\n} <div class=\"center\"></div> calc() calc()"
},
{
"answer_id": 18232641,
"author": "Ryan",
"author_id": 2246362,
"author_profile": "https://Stackoverflow.com/users/2246362",
"pm_score": 2,
"selected": false,
"text": "$.fn.center = function () {\n /// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>\n\n var element = $(this),\n elementPos = element.css('position'),\n elementParent = $(element.parent()),\n elementWidth = element.outerWidth(),\n parentWidth = elementParent.width();\n\n if (parentWidth <= elementWidth) {\n elementParent = $(elementParent.parent());\n parentWidth = elementParent.width();\n }\n\n if (elementPos === \"absolute\" || elementPos === \"fixed\") {\n element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');\n }\n };\n"
},
{
"answer_id": 19424085,
"author": "Sajitha Rathnayake",
"author_id": 2345900,
"author_profile": "https://Stackoverflow.com/users/2345900",
"pm_score": 0,
"selected": false,
"text": ".black_overlay{\n display: none;\n position: absolute;\n top: 0%;\n left: 0%;\n width: 100%;\n height: 100%;\n background-color: black;\n z-index:1001;\n -moz-opacity: 0.8;\n opacity:.80;\n filter: alpha(opacity=80);\n}\n\n.white_content {\n display: none;\n position: absolute;\n top: 25%;\n left: 25%;\n width: 50%;\n height: 50%;\n padding: 16px;\n border: 16px solid orange;\n background-color: white;\n z-index:1002;\n overflow: auto;\n}\n $(document).ready(function(){\n $(\".open\").click(function(e){\n $(\".black_overlay\").fadeIn(200);\n });\n\n});\n"
},
{
"answer_id": 25041231,
"author": "Fred K",
"author_id": 1252920,
"author_profile": "https://Stackoverflow.com/users/1252920",
"pm_score": 0,
"selected": false,
"text": "translate position: absolute;\ntransform: translate(-50%, -50%);\n"
},
{
"answer_id": 25055575,
"author": "andy_edward",
"author_id": 2765240,
"author_profile": "https://Stackoverflow.com/users/2765240",
"pm_score": 4,
"selected": false,
"text": "position <div id=\"test\" style=\"position:absolute;background-color:blue;color:white\">\n test div to center in window\n</div>\n <script type=\"text/javascript\">\n$(function(){\n $(\"#test\").position({\n of: $(window)\n });\n};\n</script>\n"
},
{
"answer_id": 31591871,
"author": "Fata1Err0r",
"author_id": 4555355,
"author_profile": "https://Stackoverflow.com/users/4555355",
"pm_score": 0,
"selected": false,
"text": "position // We add a pos parameter so we can specify which position type we want\n\n// Center it both horizontally and vertically (dead center)\njQuery.fn.center = function (pos) {\n this.css(\"position\", pos);\n this.css(\"top\", ($(window).height() / 2) - (this.outerHeight() / 2));\n this.css(\"left\", ($(window).width() / 2) - (this.outerWidth() / 2));\n return this;\n}\n\n// Center it horizontally only\njQuery.fn.centerHor = function (pos) {\n this.css(\"position\", pos);\n this.css(\"left\", ($(window).width() / 2) - (this.outerWidth() / 2));\n return this;\n}\n\n// Center it vertically only\njQuery.fn.centerVer = function (pos) {\n this.css(\"position\", pos);\n this.css(\"top\", ($(window).height() / 2) - (this.outerHeight() / 2));\n return this;\n}\n <head> <script src=\"scripts/center.js\"></script>\n $(\"#example1\").centerHor(\"absolute\")\n$(\"#example2\").centerHor(\"fixed\")\n\n$(\"#example3\").centerVer(\"absolute\")\n$(\"#example4\").centerVer(\"fixed\")\n\n$(\"#example5\").center(\"absolute\")\n$(\"#example6\").center(\"fixed\")\n"
},
{
"answer_id": 32877025,
"author": "i_a",
"author_id": 1673876,
"author_profile": "https://Stackoverflow.com/users/1673876",
"pm_score": 0,
"selected": false,
"text": "$.fn.center = function () {\n this.css(\"position\",\"absolute\");\n\n //use % so that modal window will adjust with browser resizing\n this.css(\"top\",\"50%\");\n this.css(\"left\",\"50%\");\n\n //use negative margin to center\n this.css(\"margin-left\",(-1*this.outerWidth()/2)+($(window).scrollLeft())+\"px\");\n this.css(\"margin-top\",(-1*this.outerHeight()/2)+($(window).scrollTop())+\"px\");\n\n //catch cases where object would be offscreen\n if(this.offset().top<0)this.css({\"top\":\"5px\",\"margin-top\":\"0\"});\n if(this.offset().left<0)this.css({\"left\":\"5px\",\"margin-left\":\"0\"});\n\n return this;\n };\n"
},
{
"answer_id": 33461958,
"author": "holden",
"author_id": 3712513,
"author_profile": "https://Stackoverflow.com/users/3712513",
"pm_score": 2,
"selected": false,
"text": "$(function() {\n $('#divId').css({\n 'left' : '50%',\n 'top' : '50%',\n 'position' : 'absolute',\n 'margin-left' : -$('#divId').outerWidth()/2,\n 'margin-top' : -$('#divId').outerHeight()/2\n });\n});\n"
},
{
"answer_id": 36041478,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 0,
"selected": false,
"text": "$(\"#target\").addClass(\"centered-content\")\n .wrap(\"<div class='center-outer-container'></div>\")\n .wrap(\"<div class='center-inner-container'></div>\"); body {\n margin : 0;\n background: #ccc;\n}\n\n.center-outer-container {\n position : absolute;\n display: table;\n width: 100%;\n height: 100%;\n}\n\n.center-inner-container {\n display: table-cell;\n vertical-align: middle;\n text-align: center;\n}\n\n.centered-content {\n display: inline-block;\n text-align: left;\n background: #fff;\n padding : 20px;\n border : 1px solid #000;\n} <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script>\n<div id=\"target\">Center this!</div>"
},
{
"answer_id": 36107095,
"author": "satya",
"author_id": 5229920,
"author_profile": "https://Stackoverflow.com/users/5229920",
"pm_score": 2,
"selected": false,
"text": "$(window).resize(function(){\n $('.className').css({\n position:'absolute',\n left: ($(window).width() - $('.className').outerWidth())/2,\n top: ($(window).height() - $('.className').outerHeight())/2\n });\n});\n\n// To initially run the function:\n$(window).resize();\n"
},
{
"answer_id": 49306665,
"author": "Shivam Chhetri",
"author_id": 9138195,
"author_profile": "https://Stackoverflow.com/users/9138195",
"pm_score": 2,
"selected": false,
"text": "#outer{\n display: flex;\n}\n#inner{\n margin: auto;\n}\n margin: 0 auto;\n margin: auto 0;\n"
},
{
"answer_id": 64030396,
"author": "Rayees AC",
"author_id": 13368658,
"author_profile": "https://Stackoverflow.com/users/13368658",
"pm_score": 0,
"selected": false,
"text": "CSS Flex box body.center{\n display:flex;\n align-items:center; // Vertical alignment\n justify-content:center; // Horizontal alignment\n}\n document.querySelector(\"body\").classList.add(\"center\"); body {\n margin : 0;\n height:100vh;\n width:100%;\n background: #ccc;\n}\n#main{\n background:#00cc00;\n width:100px;\n height:100px;\n}\nbody.center{\n display:flex;\n align-items:center;\n justify-content:center;\n} <body>\n <div id=\"main\"></div>\n</body>"
},
{
"answer_id": 73155953,
"author": "aji stack",
"author_id": 5755460,
"author_profile": "https://Stackoverflow.com/users/5755460",
"pm_score": 0,
"selected": false,
"text": "cadasWidth = $('.card-dashboard').innerWidth();\ncadasWidthCenter = cadasWidth/2;\n\nulmenuWidth = $('.card-dashboard ul#menu').outerWidth();\nulmenuWidthCenter = ulmenuWidth/2;\n\nulmenuStart = cadasWidthCenter - ulmenuWidthCenter;\n\n$('.card-dashboard ul#menu').css({\n 'left' : ulmenuStart,\n 'position' : 'relative'\n});\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
210,719
|
<p>I am using log.properties to configure logging for a Java app. Each class gets its own logger named after itself (e.g. com.company.program.ClassX).</p>
<p>I want to set a custom formatter for just one log, and leave the handler with the SimpleFormatter. Is this possible?</p>
<p>I am not interested in using log4j or another of the other logging suites. I am well aware of them. Nor am I interested in configuring a customer formatter for the logger through code, although if that is the only way to do it, it would be nice to know. Google isn't helping, and I am having problems testing this myself.</p>
|
[
{
"answer_id": 212785,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 0,
"selected": false,
"text": "System.out.println"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2204759/"
] |
210,725
|
<p>I have a drop down like this on my page:</p>
<pre><code><p>
<%= f.label :episode_id %><br />
<%= f.collection_select(:episode_id, @episodes, :id, :show) %>
</p>
</code></pre>
<p>An episode has an id and <code>belongs_to</code> to a show which has a name. In the dropdown, I'd like to display the show name. <code>:show.name</code> doesn't work to display the name. How do I do this?</p>
|
[
{
"answer_id": 210825,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 2,
"selected": true,
"text": "show_name def show_name\n show.name\nend\n"
},
{
"answer_id": 210918,
"author": "salt.racer",
"author_id": 757,
"author_profile": "https://Stackoverflow.com/users/757",
"pm_score": 0,
"selected": false,
"text": "episode.show.name"
},
{
"answer_id": 210920,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 0,
"selected": false,
"text": "f.select(:episode, :id, @episodes.map{|e| [e.show.name, e.id]})\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109/"
] |
210,729
|
<p>I need a data structure that can store non-overlapping ranges within a single dimension. The entire range of the dimension need not be completely covered.</p>
<p>An example would be a conference room scheduler. The dimension is time. No two schedules may overlap. The conference room isn't always scheduled. In other words, for a given time there can be at most one schedule.</p>
<p>A quick solution is for a range to store the start and end times.</p>
<pre><code>Range {
Date start
Date end
}
</code></pre>
<p>This is non-normalized and requires the container to enforce no overlapping. For two adjacent ranges, the previous' end will be redundant with the next's start.</p>
<p>Another scheme might involve storing one boundary value with each range. But for a contiguous sequence of ranges, there will always be one more boundary values than ranges. To get around this the sequence could be represented as alternating boundary values and ranges:</p>
<p>B = boundary value, r = range</p>
<blockquote>
<p>B-r-B-r-B</p>
</blockquote>
<p>The data structure might look like:</p>
<pre><code>Boundary {
Date value
Range prev
Range next
}
Range {
Boundary start
Boundary end
}
</code></pre>
<p>In essence it's a doubly linked list with alternating types.</p>
<p>Ultimately, whatever data structure I use will be represented in both memory (application code) and a relational database.</p>
<p>I'm curious what academic or industry tried solutions exists.</p>
|
[
{
"answer_id": 210750,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 1,
"selected": false,
"text": "(RoomId, StartTime)\n (boundary not between colBoudaryA and colBoundaryB)\n (startBoundary < endBoundary)\n"
},
{
"answer_id": 765420,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "WHERE NOT EXISTS (\n SELECT 1 FROM table\n WHERE BeginTime < NewBeginTime AND BeginTime + Duration > NewBeginTime\n)\nAND NOT EXISTS (\n SELECT 1 FROM table\n WHERE NewBeginTime < BeginTime AND NewBeginTime + NewDuration > BeginTime\n)\n"
},
{
"answer_id": 26112540,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 1,
"selected": false,
"text": "tstzrange ALTER TABLE \"booking\" \nADD CONSTRAINT \"overlapping_bookings\" \nEXCLUDE USING gist (\"period\" WITH &&, \"room\" WITH =);\n CREATE EXTENSION IF NOT EXISTS btree_gist"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
210,738
|
<p>Could somebody please point me in the right direction for learning how to do networking in C#/.net 3.5? Code samples and explanations are welcome. Basically I am looking for how to do asynchronous/multithreaded server/client models.</p>
<p>I am fairly comfortable with the basics in how to accomplish this in C++ with WinSock but though all of my research cannot seem to grasp this concept in C#.</p>
<p>Thanks for any assistance you can provide :)</p>
|
[
{
"answer_id": 210775,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 0,
"selected": false,
"text": "System.Net.Sockets.Socket"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,743
|
<p>How can I modify the <code>NSDatePickerElementFlags</code> for the <code>NSDatePicker</code> in row templates for <code>NSDate</code> properties returned by <code>[NSPredicateRowEditorTemplate templatesWithAttributeKeyPaths:inEntityDescription:]</code>? I would like the <code>NSDatePicker</code> to show hrs:minutes as well as the date.</p>
<p><strong>Update</strong>
I've added an answer below, gleaned from the cocoa-dev list.</p>
|
[
{
"answer_id": 210775,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 0,
"selected": false,
"text": "System.Net.Sockets.Socket"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2140/"
] |
210,761
|
<p>Upon page load I want to move the cursor to a particular field. No problem. But I also need to select and highlight the default value that is placed in that text field.</p>
|
[
{
"answer_id": 210764,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 8,
"selected": true,
"text": "var input = document.getElementById('myTextInput');\ninput.focus();\ninput.select(); <input id=\"myTextInput\" value=\"Hello world!\" />"
},
{
"answer_id": 211199,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 4,
"selected": false,
"text": "window.onload = function () {\n var input = document.getElementById('myTextInput');\n input.focus();\n input.select();\n} <input id=\"myTextInput\" value=\"Hello world!\" />"
},
{
"answer_id": 4175179,
"author": "dvo",
"author_id": 507031,
"author_profile": "https://Stackoverflow.com/users/507031",
"pm_score": 5,
"selected": false,
"text": "onFocus=\"this.select()\"\n"
},
{
"answer_id": 27326206,
"author": "pedalGeoff",
"author_id": 498685,
"author_profile": "https://Stackoverflow.com/users/498685",
"pm_score": 3,
"selected": false,
"text": "<input type=\"text\" onclick=\"this.focus();this.select()\">\n"
},
{
"answer_id": 37652888,
"author": "Vivek ab",
"author_id": 5523153,
"author_profile": "https://Stackoverflow.com/users/5523153",
"pm_score": 5,
"selected": false,
"text": "<input type=\"text\" value=\"test\" autofocus onfocus=\"this.select()\">"
},
{
"answer_id": 38147380,
"author": "Sean M",
"author_id": 1594456,
"author_profile": "https://Stackoverflow.com/users/1594456",
"pm_score": 2,
"selected": false,
"text": "<input type='text' value='hello world' id='hello-world-input'>\n $(function() {\n $('#hello-world-input').focus().select();\n});\n"
},
{
"answer_id": 51416786,
"author": "paranjothi",
"author_id": 6362807,
"author_profile": "https://Stackoverflow.com/users/6362807",
"pm_score": 0,
"selected": false,
"text": " var input = document.getElementById('myTextInput');\n input.focus();\n input.setSelectionRange( 6, 19 ); <input id=\"myTextInput\" value=\"Hello default value world!\" /> input.selectionStart = 6;\ninput.selectionEnd = 19;\n"
},
{
"answer_id": 59733850,
"author": "M. Ivanov",
"author_id": 10673830,
"author_profile": "https://Stackoverflow.com/users/10673830",
"pm_score": 0,
"selected": false,
"text": "autofocus <input type=\"text\" name=\"foo\" value=\"boo\" autofocus=\"autofocus\"> FooBoo\n<input type=\"checkbox\" name=\"foo\" value=\"boo\" autofocus=\"autofocus\"> FooBoo\n"
},
{
"answer_id": 62305440,
"author": "lifeae",
"author_id": 12887129,
"author_profile": "https://Stackoverflow.com/users/12887129",
"pm_score": 0,
"selected": false,
"text": "<form action=\"/action_page.php\">\n <input type=\"text\" id=\"fname\" name=\"fname\" autofocus>\n <input type=\"submit\">\n</form>\n"
},
{
"answer_id": 67662375,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<input type=\"text\" autofocus>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444/"
] |
210,787
|
<p>I have a xml which is max 3 levels deep. Now by using C# or Xpath what the best method to check the whether all the child nodes under a parent node are empty.</p>
<p>Thanks in Advance.</p>
|
[
{
"answer_id": 210822,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "<foo>\n <bar>\n <baz/>\n <baz>Hello, world!</baz>\n <baz><qux/></baz>\n </bar>\n</foo>\n foo/bar foo/bar/*[count(*)>0]\n foo/bar foo/bar/*[text()]\n not(foo/bar/*[count(*)>0 or text()])\n"
},
{
"answer_id": 210845,
"author": "David Hall",
"author_id": 2660,
"author_profile": "https://Stackoverflow.com/users/2660",
"pm_score": 0,
"selected": false,
"text": "\nXElement xml = new XElement(\"contacts\",\n new XElement(\"contact\",\n new XAttribute(\"contactId\", \"\"),\n new XElement(\"firstName\", \"\"),\n new XElement(\"lastName\", \"\"),\n new XElement(\"Address\",\n new XElement(\"Street\", \"\"))\n ),\n\nnew XElement(\"contact\",\n new XAttribute(\"contactId\", \"\"),\n new XElement(\"firstName\", \"\"),\n new XElement(\"lastName\", \"\")\n )\n );\n\nvar query = from c in xml.Elements()\n where c.Value != \"\"\n select c;\n\nConsole.WriteLine(xml);\nConsole.WriteLine(query.Count());\n\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28773/"
] |
210,789
|
<p>While building a small experimental HTTP server, I need to implement the persistent connection feature of HTTP 1.1 (and the pipelining feature).
How do I test it?
Using a browser like Firefox gives me little or no control, and it's hard to check.
Any ideas?</p>
<p>Thanks</p>
|
[
{
"answer_id": 210954,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 1,
"selected": false,
"text": "-k"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25645/"
] |
210,809
|
<p>Essentially my question is, does anyone know of a utility for inspecting the <strong>buffer cache</strong> in linux?</p>
|
[
{
"answer_id": 18398941,
"author": "slm",
"author_id": 33204,
"author_profile": "https://Stackoverflow.com/users/33204",
"pm_score": 4,
"selected": true,
"text": "fincore $ fincore [options] files...\n\n --pages=false Do not print pages\n --summarize When comparing multiple files, print a summary report\n --only-cached Only print stats for files that are actually in cache.\n\nroot@xxxxxx:/var/lib/mysql/blogindex# fincore --pages=false --summarize --only-cached * \nstats for CLUSTER_LOG_2010_05_21.MYI: file size=93840384 , total pages=22910 , cached pages=1 , cached size=4096, cached perc=0.004365 \nstats for CLUSTER_LOG_2010_05_22.MYI: file size=417792 , total pages=102 , cached pages=1 , cached size=4096, cached perc=0.980392 \nstats for CLUSTER_LOG_2010_05_23.MYI: file size=826368 , total pages=201 , cached pages=1 , cached size=4096, cached perc=0.497512 \nstats for CLUSTER_LOG_2010_05_24.MYI: file size=192512 , total pages=47 , cached pages=1 , cached size=4096, cached perc=2.127660 \n...\n"
},
{
"answer_id": 26860348,
"author": "Highstaker",
"author_id": 2052138,
"author_profile": "https://Stackoverflow.com/users/2052138",
"pm_score": 2,
"selected": false,
"text": "vmtouch [file or folder you want to check for presence in cache]"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10747/"
] |
210,820
|
<p>I have a webpage that redirects to another webpage like this:</p>
<pre><code>http://www.myOtherServer.com/Sponsor.php?RedirectPage=http://mylink.com/whereIwasgoingtogo.html
</code></pre>
<p>Then the Sponsor.php page displays an ad with a link saying "Continue to your page" that links to the passed in RedirectPage. Are there security/spoofing issues that could come from this? What is the best way to handle this? (note that the user is not logged in to either site)</p>
|
[
{
"answer_id": 1089103,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 4,
"selected": true,
"text": " http://cnn.com/sponsor.php?redirectpage=http://bit.ly/jh2l14\n http://cnn.com/sponsor.php?redirectpage=javascript:location.href='http://attacker.com/' + document.cookie\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
210,821
|
<p>I have read the post <a href="http://www.julienlecomte.net/blog/2007/10/28/" rel="noreferrer">here</a> about using setTimeout() during intensive DOM processing (using JavaScript), but how can I integrate this function with the below code? The below code works fine for a small number of options, but when the number of options gets too big my "please wait" animated GIF freezes while the local JavaScript is processing. Thanks!</p>
<pre><code>function appendToSelect() {
$("#mySelect").children().remove() ;
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
var j = 1 ;
for (var i = 1; i < obj.data.length; i++) {
$("#mySelect").append(
'<option value="' + obj.data[i].value + '">'
+ obj.data[i].name
+ '</option>'
);
}
}
</code></pre>
|
[
{
"answer_id": 210968,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 4,
"selected": false,
"text": "function processLoop( actionFunc, numTimes, doneFunc ) {\n var i = 0;\n var f = function () {\n if (i < numTimes) {\n actionFunc( i++ ); // closure on i\n setTimeout( f, 10 )\n } \n else if (doneFunc) { \n doneFunc();\n }\n };\n f();\n}\n function appendToSelect () {\n\n $(\"#mySelect\").children().remove() ;\n $(\"#mySelect\").html(\n '<option selected value=\"' + obj.data[0].value + '\">'\n + obj.data[0].name\n + '</option>'\n );\n var j = 1 ;\n\n processLoop(function (i){\n $(\"#mySelect\").append(\n '<option value=\"' + obj.data[i].value + '\">'\n + obj.data[i].name\n + '</option>'\n ); \n }, obj.data.length);\n\n}\n"
},
{
"answer_id": 210994,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 6,
"selected": true,
"text": "function appendToSelect() {\n $(\"#mySelect\").children().remove();\n $(\"#mySelect\").html(\n '<option selected value=\"'+obj.data[0].value+'\">'\n + obj.data[0].name\n + '</option>'\n );\n obj.data.splice(0, 1); // we only want remaining data\n var appendOptions = function() {\n var dataChunk = obj.data.splice(0, 10); // configure this last number (the size of the 'chunk') to suit your needs\n for(var i = 0; i < dataChunk.length; i++) {\n $(\"#mySelect\").append(\n '<option value=\"' + dataChunk[i].value + '\">'\n + dataChunk[i].name\n + '</option>'\n );\n }\n if(obj.data.length > 0) {\n setTimeout(appendOptions, 100); // change time to suit needs\n }\n };\n appendOptions(); // kicks it off\n}\n function incrementallyProcess(workerCallback, data, chunkSize, timeout, completionCallback) {\n var itemIndex = 0;\n (function() {\n var remainingDataLength = (data.length - itemIndex);\n var currentChunkSize = (remainingDataLength >= chunkSize) ? chunkSize : remainingDataLength;\n if(itemIndex < data.length) {\n while(currentChunkSize--) {\n workerCallback(data[itemIndex++]);\n }\n setTimeout(arguments.callee, timeout);\n } else if(completionCallback) {\n completionCallback();\n }\n })();\n}\n\nfunction appendToSelect() {\n $(\"#mySelect\").children().remove();\n $(\"#mySelect\").html(\n '<option selected value=\"' + obj.data[0].value + '\">'\n + obj.data[0].name\n + '</option>'\n );\n obj.data.splice(0,1); // we only want remaining data \n incrementallyProcess(function(data) {\n $(\"#mySelect\").append(\n '<option value=\"' + data.value + '\">'\n + data.name\n + '</option>'\n );\n }, obj.data, 10, 100, removeAnimatedGifFunction); // last function not required...\n}\n"
},
{
"answer_id": 1610043,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 2,
"selected": false,
"text": "function appendToSelect() {\n $(\"#mySelect\").children().remove() ;\n $(\"#mySelect\").html(\n '<option selected value=\"' + obj.data[0].value + '\">'\n + obj.data[0].name\n + '</option>'\n );\n\n /////////////////////////////\n var i = 1;\n $.whileAsync({\n test: function(){ i < obj.data.length; }\n loop: function()\n {\n $(\"#mySelect\").append(\n '<option value=\"' + obj.data[i].value + '\">'\n + obj.data[i].name\n + '</option>'\n ); \n i++;\n }\n });\n /////////////////////////////\n}\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
210,826
|
<p>I have a mobile .NET solution and decided to sign the assemblies.
Compilation completes without errors but gives the warning</p>
<p><strong>'CompactUI.Business.PocketPC.asmmeta, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not signed correctly.</strong></p>
<p>The application is working fine but I can't open the designer for forms using this assembly anymore. Again the designer says</p>
<p><strong>'CompactUI.Business.PocketPC.asmmeta, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not signed correctly.</strong> </p>
<p>with the stack information: </p>
<p>at Microsoft.CompactFramework.Build.AsmmetaBindingService.GetAsmmetaAssembly(String sourceAssemblyPath, Boolean verify)
at Microsoft.CompactFramework.Build.AsmmetaBindingService.LoadAsmMetaAssembly(Assembly sourceAssembly, String hintPath, IDeviceTypeResolutionService resolver)
at Microsoft.CompactFramework.Build.MetadataService.GetAsmmetaType(Type sourceType)
at Microsoft.CompactFramework.Build.MetadataService.GetTypeAttributes(Type desktopType)
at Microsoft.CompactFramework.Design.DeviceCustomTypeDescriptor.GetAttributes()
...</p>
<p>What is causing this? </p>
<p><strong>Edit: Nicholas suggestion is not solving the problem</strong></p>
<p>I've got a Form that contains common properties which is base for every form in the presentation layer</p>
<pre><code>public class CustomForm : Form
{
...
}
</code></pre>
<p>This form is in the business layer that causes the warning. Every form that inherits from this base form causes the problem when viewing in the designer.</p>
|
[
{
"answer_id": 224328,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 1,
"selected": false,
"text": "null"
},
{
"answer_id": 225094,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": -1,
"selected": false,
"text": "* The assembly does not have a strong name.\n\n* The assembly was altered after signing.\n\n* The assembly is delay-signed.\n\n* The assembly was incorrectly signed, or signing failed.\n\n* The assembly requires registry settings to pass verification. For example, the Strong Name tool (Sn.exe) was used to skip verification for the assembly.\n * Its origins cannot be verified.\n\n* The common language runtime cannot warn users if the contents of the assembly have been altered.\n\n* It cannot be loaded into the global assembly cache.\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14027/"
] |
210,827
|
<p>I need to ask for input in console and wait for few sec may be a min after that I need to default to some value. How can basically time our on console input in c# and proceed with default settings? If you have sample code that would be great.</p>
|
[
{
"answer_id": 210859,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 2,
"selected": false,
"text": "static void Main(string[] args)\n {\n System.Timers.Timer timer = new System.Timers.Timer(60000);\n timer.Elapsed += new System.Timers.ElapsedEventHandler(T_Elapsed);\n timer.Start();\n var i = Console.ReadLine();\n if (string.IsNullOrEmpty(i)) \n {\n timer.Stop();\n Console.WriteLine(\"{0}\", i);\n }\n }\n\n static void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n {\n Console.WriteLine(\"Defult Values Used\");\n var T = (Timer)sender;\n T.Stop;\n\n }\n"
},
{
"answer_id": 212325,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 2,
"selected": false,
"text": " static void Main(string[] args)\n {\n Console.WriteLine(\"Please enter your name \");\n string input;\n\n if (TryReadLine(out input, 10000, true))\n {\n Console.WriteLine(input);\n }\n else\n {\n Console.WriteLine(\"[DEFAULT]\");\n }\n\n Console.ReadKey(true);\n }\n\n const string timerString = \"[{0} seconds until default value is used]\";\n\n public static bool TryReadLine(out string s, double timeout, bool showTimer)\n {\n DateTime timeoutDateTime = DateTime.Now.AddMilliseconds(10000);\n DateTime nextTimer = DateTime.Now;\n while (DateTime.Now < timeoutDateTime)\n {\n if (Console.KeyAvailable)\n {\n ClearTimer(timeoutDateTime);\n s = Console.ReadLine();\n return true;\n }\n\n if (showTimer && DateTime.Now > nextTimer)\n {\n WriteTimer(string.Format(timerString, (timeoutDateTime - DateTime.Now).Seconds));\n nextTimer = DateTime.Now.AddSeconds(1);\n }\n }\n\n ClearTimer(timeoutDateTime);\n s = null;\n return false;\n }\n\n private static void ClearTimer(DateTime timeoutDateTime)\n {\n WriteTimer(new string(' ', string.Format(timerString, (timeoutDateTime - DateTime.Now).Seconds).Length));\n }\n\n private static void WriteTimer(string s)\n {\n int cursorLeft = Console.CursorLeft;\n Console.CursorLeft = 0;\n Console.CursorTop += 1;\n Console.Write(s);\n Console.CursorLeft = cursorLeft;\n Console.CursorTop -= 1;\n }\n}\n static void Main(string[] args)\n {\n string input;\n Console.Write(\"Please enter your name (\");\n int timerPromptStart = Console.CursorLeft;\n Console.Write(\" seconds left): \");\n if (TryReadLine(out input, 10000, delegate(TimeSpan timeSpan)\n {\n int inputPos = Console.CursorLeft;\n Console.CursorLeft = timerPromptStart;\n Console.Write(timeSpan.Seconds.ToString(\"000\"));\n Console.CursorLeft = inputPos;\n },\n 1000))\n {\n Console.WriteLine(input);\n }\n else\n {\n Console.WriteLine(\"DEFAULT\");\n }\n while (true) { }\n }\n\n /// <summary>\n /// Tries to read a line of input from the Console.\n /// </summary>\n /// <param name=\"s\">The string to put the input into.</param>\n /// <param name=\"timeout\">The time in milliseconds before the attempt fails.</param>\n /// <returns>Whether the user inputted a line before the timeout.</returns>\n public static bool TryReadLine(out string s, double timeout)\n {\n return TryReadLine(out s, timeout, null, 0);\n }\n\n /// <summary>\n /// Tries to read a line of input from the Console.\n /// </summary>\n /// <param name=\"s\">The string to put the input into.</param>\n /// <param name=\"timeout\">The time in milliseconds before the attempt fails.</param>\n /// <param name=\"timerCallback\">A function to call every callbackInterval.</param>\n /// <param name=\"callbackInterval\">The length of time between calls to timerCallback.</param>\n /// <returns>Whether the user inputted a line before the timeout.</returns>\n public static bool TryReadLine(out string s, double timeout, Action<TimeSpan> timerCallback, double callbackInterval)\n {\n const int tabLength = 6;\n\n StringBuilder inputBuilder = new StringBuilder();\n int readStart = Console.CursorLeft;\n int lastLength = 0;\n bool isInserting = true;\n DateTime endTime = DateTime.Now.AddMilliseconds(timeout);\n DateTime nextCallback = DateTime.Now;\n while (DateTime.Now < endTime)\n {\n if (timerCallback != null && DateTime.Now > nextCallback)\n {\n nextCallback = DateTime.Now.AddMilliseconds(callbackInterval);\n timerCallback((endTime - DateTime.Now));\n }\n\n if (Console.KeyAvailable)\n {\n ConsoleKeyInfo key = Console.ReadKey(true);\n switch (key.Key)\n {\n case ConsoleKey.Enter:\n Console.WriteLine();\n s = inputBuilder.ToString();\n return true;\n\n case ConsoleKey.Backspace:\n if (Console.CursorLeft > readStart)\n {\n Console.CursorLeft -= 1;\n inputBuilder.Remove(Console.CursorLeft - readStart, 1);\n }\n break;\n\n case ConsoleKey.Delete:\n if (Console.CursorLeft < readStart + inputBuilder.Length)\n {\n inputBuilder.Remove(Console.CursorLeft - readStart, 1);\n }\n break;\n\n case ConsoleKey.Tab:\n // Tabs are very difficult to handle properly, so we'll simply replace it with spaces.\n AddOrInsert(inputBuilder, new String(' ', tabLength), isInserting, readStart);\n Console.CursorLeft += tabLength;\n break;\n\n case ConsoleKey.Escape:\n Console.CursorLeft = readStart;\n inputBuilder = new StringBuilder();\n break;\n\n case ConsoleKey.Insert:\n isInserting = !isInserting;\n // This may be dependant on a variable somewhere.\n if (isInserting)\n {\n Console.CursorSize = 25;\n }\n else\n {\n Console.CursorSize = 50;\n }\n break;\n\n case ConsoleKey.Home:\n Console.CursorLeft = readStart;\n break;\n\n case ConsoleKey.End:\n Console.CursorLeft = readStart + inputBuilder.Length;\n break;\n\n case ConsoleKey.LeftArrow:\n if (Console.CursorLeft > readStart)\n {\n Console.CursorLeft -= 1;\n }\n break;\n\n case ConsoleKey.RightArrow:\n if (Console.CursorLeft < readStart + inputBuilder.Length)\n {\n Console.CursorLeft += 1;\n }\n break;\n\n case ConsoleKey.UpArrow:\n // N.B. We can't handle Up like we normally would as we don't know the last console input.\n // You might want to handle this so it works appropriately within your own application.\n break;\n\n case ConsoleKey.PageUp:\n case ConsoleKey.PageDown:\n case ConsoleKey.PrintScreen:\n case ConsoleKey.LeftWindows:\n case ConsoleKey.RightWindows:\n case ConsoleKey.Sleep:\n case ConsoleKey.F1:\n case ConsoleKey.F2:\n case ConsoleKey.F3:\n case ConsoleKey.F4:\n case ConsoleKey.F5:\n case ConsoleKey.F6:\n case ConsoleKey.F7:\n case ConsoleKey.F8:\n case ConsoleKey.F9:\n case ConsoleKey.F10:\n case ConsoleKey.F11:\n case ConsoleKey.F12:\n case ConsoleKey.F13:\n case ConsoleKey.F14:\n case ConsoleKey.F15:\n case ConsoleKey.F16:\n case ConsoleKey.F17:\n case ConsoleKey.F18:\n case ConsoleKey.F19:\n case ConsoleKey.F20:\n case ConsoleKey.F21:\n case ConsoleKey.F22:\n case ConsoleKey.F23:\n case ConsoleKey.F24:\n case ConsoleKey.BrowserBack:\n case ConsoleKey.BrowserForward:\n case ConsoleKey.BrowserStop:\n case ConsoleKey.BrowserRefresh:\n case ConsoleKey.BrowserSearch:\n case ConsoleKey.BrowserFavorites:\n case ConsoleKey.BrowserHome:\n case ConsoleKey.VolumeMute:\n case ConsoleKey.VolumeUp:\n case ConsoleKey.VolumeDown:\n case ConsoleKey.MediaNext:\n case ConsoleKey.MediaPrevious:\n case ConsoleKey.MediaStop:\n case ConsoleKey.MediaPlay:\n case ConsoleKey.LaunchMail:\n case ConsoleKey.LaunchMediaSelect:\n case ConsoleKey.LaunchApp1:\n case ConsoleKey.LaunchApp2:\n case ConsoleKey.Play:\n case ConsoleKey.Zoom:\n case ConsoleKey.NoName:\n case ConsoleKey.Pa1:\n // These keys shouldn't do anything.\n break;\n\n case ConsoleKey.Clear:\n case ConsoleKey.Pause:\n case ConsoleKey.Select:\n case ConsoleKey.Print:\n case ConsoleKey.Execute:\n case ConsoleKey.Process:\n case ConsoleKey.Help:\n case ConsoleKey.Applications:\n case ConsoleKey.Packet:\n case ConsoleKey.Attention:\n case ConsoleKey.CrSel:\n case ConsoleKey.ExSel:\n case ConsoleKey.EraseEndOfFile:\n case ConsoleKey.OemClear:\n // I'm not sure what these do.\n break;\n\n default:\n Console.Write(key.KeyChar);\n AddOrInsert(inputBuilder, key.KeyChar.ToString(), isInserting, readStart);\n break;\n }\n\n // Write what has current been typed in back out to the Console.\n // We write out everything after the cursor to handle cases where the current input string is shorter than before\n // (i.e. the user deleted stuff).\n // There is probably a more efficient way to do this.\n int oldCursorPos = Console.CursorLeft;\n Console.CursorLeft = readStart;\n Console.Write(inputBuilder.ToString());\n if (lastLength > inputBuilder.Length)\n {\n Console.Write(new String(' ', lastLength - inputBuilder.Length));\n }\n lastLength = inputBuilder.Length;\n Console.CursorLeft = oldCursorPos;\n }\n }\n\n // The timeout period was reached.\n Console.WriteLine();\n s = null;\n return false;\n }\n\n // This is a rather ugly helper method to add text to the inputBuilder, either inserting or appending as appropriate.\n private static void AddOrInsert(StringBuilder inputBuilder, string s, bool insert, int readStart)\n {\n if (Console.CursorLeft < readStart + inputBuilder.Length + (insert ? -1 : 1))\n {\n if (!insert)\n {\n inputBuilder.Remove(Console.CursorLeft - 1 - readStart, 1);\n }\n inputBuilder.Insert(Console.CursorLeft - 1 - readStart, s);\n }\n else\n {\n inputBuilder.Append(s);\n }\n }\n}\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13432/"
] |
210,829
|
<p>What is an NP-complete problem? Why is it such an important topic in computer science?</p>
|
[
{
"answer_id": 210892,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 5,
"selected": false,
"text": "P NP NP-Complete"
},
{
"answer_id": 210932,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 4,
"selected": false,
"text": "(a or b) and (b or !c) and (d or !e or f) ...\n (a or !b or !c) and (!a or b or !d) and (b or !c or d) ...\n"
},
{
"answer_id": 313523,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 9,
"selected": false,
"text": "NP"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
210,835
|
<p>What does the term <b>referential transparency</b> mean? I've heard it described as "it means you can replace equals with equals" but this seems like an inadequate explanation.</p>
|
[
{
"answer_id": 210871,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 7,
"selected": false,
"text": "int plusOne(int x)\n{\n return x+1;\n}\n //global G\nint G = 10;\n\nint plusG(int x)\n{//G can be modified externally returning different values.\n return x + G;\n}\n"
},
{
"answer_id": 35706014,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "data Nat = Zero | Suc Nat E[·] [·]+1 [·]++ [[·]] E[·] E1 E2 [[E1]] = [[E2]] [[E[E1]]] = [[E[E2]]] E1 E2 E1 = E2 E[E1] = E[E2] E[·] = [[·]] [[·]] E1 E2 [·]++ [[·]] : Expression -> (State -> State x Value) Value Expression State [[x]] [[x++]] [·]++ [[·]]"
},
{
"answer_id": 65179712,
"author": "Ari Fordsham",
"author_id": 12153248,
"author_profile": "https://Stackoverflow.com/users/12153248",
"pm_score": 0,
"selected": false,
"text": "ST constexpr"
},
{
"answer_id": 66768214,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 2,
"selected": false,
"text": "let counter=0\nfunction count(){\n return counter++\n}\n function count(counter){\n return counter+1\n }\n"
},
{
"answer_id": 73367043,
"author": "Liam Neeson",
"author_id": 17090996,
"author_profile": "https://Stackoverflow.com/users/17090996",
"pm_score": 0,
"selected": false,
"text": "Int plusFive(int x){\n\nreturn x+5\n\n}\n Int output = plusFive(10) Int output = 15"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
210,836
|
<p>In xp 32bit this line compiles with not problem however in vista 64bit this line:</p>
<pre><code>m_FuncAddr = ::GetProcAddress (somthing);
</code></pre>
<p>gives the following error</p>
<blockquote>
<p>error C2440: '=' : cannot convert from
'FARPROC' to 'int (__cdecl *)(void)'</p>
</blockquote>
<p>GetProcAddress is defined as</p>
<pre><code>WINBASEAPI FARPROC WINAPI GetProcAddress (somthing)
</code></pre>
<p>And m_FuncAddr as</p>
<pre><code>int (WINAPI *m_FuncAddr)();
</code></pre>
<p>From what I understand both are stdcall's.</p>
<p>To avoid the error I had to put</p>
<pre><code>m_FuncAddr = (int (__cdecl *)(void))::GetProcAddress(somthing);
</code></pre>
<p>My Question:</p>
<p>If both m_FuncAddr and GetProcAddress have the stdcall calling convention why do I have to 'recall' it with cdecl ?</p>
<p>Is it possible that the VS project setting 'default calling convention (which is set to cdecl) over-rides the assignemet statment above ?</p>
<p>Thanks in advance!</p>
<p>[Edit]</p>
<p>To clerfiy the question:</p>
<p>On one side of the equation (say side 1) i have </p>
<pre><code>int __stdcall * m_FuncAddr
</code></pre>
<p>On other side (side 2)</p>
<pre><code>INT_PTR far __stdcall GetProcAddress
</code></pre>
<p>So how is it that i have to cast side 2 with cdecl if both are stdcalls ?
Or am I not getting something ?</p>
|
[
{
"answer_id": 210857,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 2,
"selected": false,
"text": "typedef int (WINAPI *FFuncType)();\nFFuncType m_FuncAddr;\nm_FuncAddr = (FFuncType)::GetProcAddress (somthing);\n"
},
{
"answer_id": 210864,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 3,
"selected": true,
"text": "#ifdef _WIN64\ntypedef INT_PTR (FAR WINAPI *FARPROC)();\n INT_PTR (WINAPI *m_FuncAddr)();\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14587/"
] |
210,837
|
<p>How do I share state amongst TestMethods in MSTest. These tests would be run as Ordered Tests and in sequence.</p>
<pre><code> private TestContext testContext;
public TestContext TestContext
{
get { return this.testContext; }
set { this.testContext = value;}
}
[TestMethod]
public void Subscribe()
{
bool subscribed = true;
TestContext.Properties.Add("subscribed", subscribed);
Assert.IsTrue(subscribed == true, string.Format("Subscribed...{0}", this.GetHashCode()));
}
[TestMethod]
public void GenerateEvent()
{
bool subscribed = (bool)TestContext.Properties["subscribed"];
Assert.IsTrue(subscribed == true, string.Format("Subscribed...{0}", this.GetHashCode()));
}
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 403466,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "private static List<string> SharedValues = new List<string>();\n\n[TestMethod]\npublic void TestMethod1()\n{\n SharedValues.Add(\"Awesome!\");\n}\n\n[TestMethod]\npublic void TestMethod2()\n{\n SharedValues.Add(\"Thanks for the answer!\");\n}\n\n[TestMethod]\npublic void TestMethod3()\n{\n Assert.IsTrue(SharedValues.Contains(\"Awesome!\"));\n Assert.IsTrue(SharedValues.Contains(\"Thanks for the answer!\"));\n}\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28413/"
] |
210,881
|
<p>I have a KML file overlay on an embedded Google Map using the GGeoXml object. I'd like to be able to access specific placemarks in the KML file from Javascript (for example to highlight a selected polygon on the map in response to user action). </p>
<p>Ideally what I'd like to do is something like this (pseudo-code):</p>
<pre><code> geoXml.getPlacemarkByName('Foo').focus();
</code></pre>
<p>Unforunately the <a href="http://code.google.com/apis/maps/documentation/reference.html#GGeoXml" rel="nofollow noreferrer">Google Maps API</a> doesn't seem to expose the placemarks or any other internals of the KML overlay. Does anyone have any thoughts as to how I might accomplish this? I don't know anything about how the overlays are implemented internally, but it seems like there might be a hack that would let me do this.</p>
<p>I'm also using jQuery FWIW.</p>
|
[
{
"answer_id": 375726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "GEvent.addListener(map, 'addoverlay', function(o) {\n kmlmarkers.push(o);\n}\n"
},
{
"answer_id": 422581,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "GEvent.addListener(map, 'addoverlay', function(obj)\n{ if (!obj) {\n alert(\"Cannot describe a null object\");\n return;\n }\n var str = \"\";\n\n for ( var prop in obj) {\n str += prop + \" = \" + obj[prop] + \",\\n\";\n }\n alert(str);\n });\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
210,882
|
<p>I'm being asked to add queryability to a database (Oracle) filled with mostly binary data.
So I need to be able to query binary ranges within a blobs of a few kilobytes. I've never done this before, so I'm wondering what are some good practices and pitfalls to consider when starting a project like this.</p>
<p>Thanks</p>
|
[
{
"answer_id": 210963,
"author": "Jamie Love",
"author_id": 27308,
"author_profile": "https://Stackoverflow.com/users/27308",
"pm_score": 2,
"selected": false,
"text": "create or replace function retrieve_data_from_blob (\n b blob\n , tag_code\n)\nas\n lw long raw;\n data varchar(30000);\n result varchar(100);\n amount pls_integer := 30000;\nbegin\n -- covert blob to long raw.\n -- amount will hold total bytes read.\n dbms_lob.read(b, amount, 1, lw);\n data := util_raw.rawtohex(lw);\n -- retrieve_embedded retrieves data tagged with tag_code\n -- from internal binary structure by reading hex data\n return retrieve_embedded(data, tag_code);\nend;\n/\n substr(data, 1, 8) to_number(hexdata, 'xxxxxxxx')"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
210,922
|
<p>What control type should I use - <code>Image</code>, <code>MediaElement</code>, etc.?</p>
|
[
{
"answer_id": 213786,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 5,
"selected": false,
"text": "PictureBox System.Windows.Forms WindowsFormsIntegration System.Drawing <Window x:Class=\"GifExample.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:wfi=\"clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration\"\n xmlns:winForms=\"clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms\"\n Loaded=\"Window_Loaded\" >\n <Grid>\n <wfi:WindowsFormsHost>\n <winForms:PictureBox x:Name=\"pictureBoxLoading\">\n </winForms:PictureBox>\n </wfi:WindowsFormsHost>\n </Grid>\n</Window >\n Window_Loaded pictureBoxLoading.ImageLocation private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n pictureBoxLoading.ImageLocation = \"../Images/mygif.gif\";\n}\n MediaElement Image"
},
{
"answer_id": 1134340,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "FrameIndex ChangingFrameIndex FrameIndex class GifImage : Image\n{\n private bool _isInitialized;\n private GifBitmapDecoder _gifDecoder;\n private Int32Animation _animation;\n\n public int FrameIndex\n {\n get { return (int)GetValue(FrameIndexProperty); }\n set { SetValue(FrameIndexProperty, value); }\n }\n\n private void Initialize()\n {\n _gifDecoder = new GifBitmapDecoder(new Uri(\"pack://application:,,,\" + this.GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, _gifDecoder.Frames.Count / 10, (int)((_gifDecoder.Frames.Count / 10.0 - _gifDecoder.Frames.Count / 10) * 1000))));\n _animation.RepeatBehavior = RepeatBehavior.Forever;\n this.Source = _gifDecoder.Frames[0];\n\n _isInitialized = true;\n }\n\n static GifImage()\n {\n VisibilityProperty.OverrideMetadata(typeof (GifImage),\n new FrameworkPropertyMetadata(VisibilityPropertyChanged));\n }\n\n private static void VisibilityPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n {\n if ((Visibility)e.NewValue == Visibility.Visible)\n {\n ((GifImage)sender).StartAnimation();\n }\n else\n {\n ((GifImage)sender).StopAnimation();\n }\n }\n\n public static readonly DependencyProperty FrameIndexProperty =\n DependencyProperty.Register(\"FrameIndex\", typeof(int), typeof(GifImage), new UIPropertyMetadata(0, new PropertyChangedCallback(ChangingFrameIndex)));\n\n static void ChangingFrameIndex(DependencyObject obj, DependencyPropertyChangedEventArgs ev)\n {\n var gifImage = obj as GifImage;\n gifImage.Source = gifImage._gifDecoder.Frames[(int)ev.NewValue];\n }\n\n /// <summary>\n /// Defines whether the animation starts on it's own\n /// </summary>\n public bool AutoStart\n {\n get { return (bool)GetValue(AutoStartProperty); }\n set { SetValue(AutoStartProperty, value); }\n }\n\n public static readonly DependencyProperty AutoStartProperty =\n DependencyProperty.Register(\"AutoStart\", typeof(bool), typeof(GifImage), new UIPropertyMetadata(false, AutoStartPropertyChanged));\n\n private static void AutoStartPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n {\n if ((bool)e.NewValue)\n (sender as GifImage).StartAnimation();\n }\n\n public string GifSource\n {\n get { return (string)GetValue(GifSourceProperty); }\n set { SetValue(GifSourceProperty, value); }\n }\n\n public static readonly DependencyProperty GifSourceProperty =\n DependencyProperty.Register(\"GifSource\", typeof(string), typeof(GifImage), new UIPropertyMetadata(string.Empty, GifSourcePropertyChanged));\n\n private static void GifSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n {\n (sender as GifImage).Initialize();\n }\n\n /// <summary>\n /// Starts the animation\n /// </summary>\n public void StartAnimation()\n {\n if (!_isInitialized)\n this.Initialize();\n\n BeginAnimation(FrameIndexProperty, _animation);\n }\n\n /// <summary>\n /// Stops the animation\n /// </summary>\n public void StopAnimation()\n {\n BeginAnimation(FrameIndexProperty, null);\n }\n}\n <controls:GifImage x:Name=\"gifImage\" Stretch=\"None\" GifSource=\"/SomeImage.gif\" AutoStart=\"True\" />\n"
},
{
"answer_id": 1660225,
"author": "Mike Eshva",
"author_id": 156991,
"author_profile": "https://Stackoverflow.com/users/156991",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Control the \"Images\", which supports animated GIF.\n/// </summary>\npublic class AnimatedImage : Image\n{\n #region Public properties\n\n /// <summary>\n /// Gets / sets the number of the current frame.\n /// </summary>\n public int FrameIndex\n {\n get { return (int) GetValue(FrameIndexProperty); }\n set { SetValue(FrameIndexProperty, value); }\n }\n\n /// <summary>\n /// Gets / sets the image that will be drawn.\n /// </summary>\n public new ImageSource Source\n {\n get { return (ImageSource) GetValue(SourceProperty); }\n set { SetValue(SourceProperty, value); }\n }\n\n #endregion\n\n #region Protected interface\n\n /// <summary>\n /// Provides derived classes an opportunity to handle changes to the Source property.\n /// </summary>\n protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs aEventArgs)\n {\n ClearAnimation();\n\n BitmapImage lBitmapImage = aEventArgs.NewValue as BitmapImage;\n\n if (lBitmapImage == null)\n {\n ImageSource lImageSource = aEventArgs.NewValue as ImageSource;\n base.Source = lImageSource;\n return;\n }\n\n if (!IsAnimatedGifImage(lBitmapImage))\n {\n base.Source = lBitmapImage;\n return;\n }\n\n PrepareAnimation(lBitmapImage);\n }\n\n #endregion\n\n #region Private properties\n\n private Int32Animation Animation { get; set; }\n private GifBitmapDecoder Decoder { get; set; }\n private bool IsAnimationWorking { get; set; }\n\n #endregion\n\n #region Private methods\n\n private void ClearAnimation()\n {\n if (Animation != null)\n {\n BeginAnimation(FrameIndexProperty, null);\n }\n\n IsAnimationWorking = false;\n Animation = null;\n Decoder = null;\n }\n\n private void PrepareAnimation(BitmapImage aBitmapImage)\n {\n Debug.Assert(aBitmapImage != null);\n\n if (aBitmapImage.UriSource != null)\n {\n Decoder = new GifBitmapDecoder(\n aBitmapImage.UriSource,\n BitmapCreateOptions.PreservePixelFormat,\n BitmapCacheOption.Default);\n }\n else\n {\n aBitmapImage.StreamSource.Position = 0;\n Decoder = new GifBitmapDecoder(\n aBitmapImage.StreamSource,\n BitmapCreateOptions.PreservePixelFormat,\n BitmapCacheOption.Default);\n }\n\n Animation =\n new Int32Animation(\n 0,\n Decoder.Frames.Count - 1,\n new Duration(\n new TimeSpan(\n 0,\n 0,\n 0,\n Decoder.Frames.Count / 10,\n (int) ((Decoder.Frames.Count / 10.0 - Decoder.Frames.Count / 10) * 1000))))\n {\n RepeatBehavior = RepeatBehavior.Forever\n };\n\n base.Source = Decoder.Frames[0];\n BeginAnimation(FrameIndexProperty, Animation);\n IsAnimationWorking = true;\n }\n\n private bool IsAnimatedGifImage(BitmapImage aBitmapImage)\n {\n Debug.Assert(aBitmapImage != null);\n\n bool lResult = false;\n if (aBitmapImage.UriSource != null)\n {\n BitmapDecoder lBitmapDecoder = BitmapDecoder.Create(\n aBitmapImage.UriSource,\n BitmapCreateOptions.PreservePixelFormat,\n BitmapCacheOption.Default);\n lResult = lBitmapDecoder is GifBitmapDecoder;\n }\n else if (aBitmapImage.StreamSource != null)\n {\n try\n {\n long lStreamPosition = aBitmapImage.StreamSource.Position;\n aBitmapImage.StreamSource.Position = 0;\n GifBitmapDecoder lBitmapDecoder =\n new GifBitmapDecoder(\n aBitmapImage.StreamSource,\n BitmapCreateOptions.PreservePixelFormat,\n BitmapCacheOption.Default);\n lResult = lBitmapDecoder.Frames.Count > 1;\n\n aBitmapImage.StreamSource.Position = lStreamPosition;\n }\n catch\n {\n lResult = false;\n }\n }\n\n return lResult;\n }\n\n private static void ChangingFrameIndex\n (DependencyObject aObject, DependencyPropertyChangedEventArgs aEventArgs)\n {\n AnimatedImage lAnimatedImage = aObject as AnimatedImage;\n\n if (lAnimatedImage == null || !lAnimatedImage.IsAnimationWorking)\n {\n return;\n }\n\n int lFrameIndex = (int) aEventArgs.NewValue;\n ((Image) lAnimatedImage).Source = lAnimatedImage.Decoder.Frames[lFrameIndex];\n lAnimatedImage.InvalidateVisual();\n }\n\n /// <summary>\n /// Handles changes to the Source property.\n /// </summary>\n private static void OnSourceChanged\n (DependencyObject aObject, DependencyPropertyChangedEventArgs aEventArgs)\n {\n ((AnimatedImage) aObject).OnSourceChanged(aEventArgs);\n }\n\n #endregion\n\n #region Dependency Properties\n\n /// <summary>\n /// FrameIndex Dependency Property\n /// </summary>\n public static readonly DependencyProperty FrameIndexProperty =\n DependencyProperty.Register(\n \"FrameIndex\",\n typeof (int),\n typeof (AnimatedImage),\n new UIPropertyMetadata(0, ChangingFrameIndex));\n\n /// <summary>\n /// Source Dependency Property\n /// </summary>\n public new static readonly DependencyProperty SourceProperty =\n DependencyProperty.Register(\n \"Source\",\n typeof (ImageSource),\n typeof (AnimatedImage),\n new FrameworkPropertyMetadata(\n null,\n FrameworkPropertyMetadataOptions.AffectsRender |\n FrameworkPropertyMetadataOptions.AffectsMeasure,\n OnSourceChanged));\n\n #endregion\n}\n"
},
{
"answer_id": 2614025,
"author": "Ken",
"author_id": 313536,
"author_profile": "https://Stackoverflow.com/users/313536",
"pm_score": 3,
"selected": false,
"text": " /// <summary> \n/// Элемент управления \"Изображения\", поддерживающий анимированные GIF. \n/// </summary> \npublic class AnimatedImage : Image\n{\n static AnimatedImage()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimatedImage), new FrameworkPropertyMetadata(typeof(AnimatedImage)));\n }\n\n #region Public properties\n\n /// <summary> \n /// Получает/устанавливает номер текущего кадра. \n /// </summary> \n public int FrameIndex\n {\n get { return (int)GetValue(FrameIndexProperty); }\n set { SetValue(FrameIndexProperty, value); }\n }\n\n /// <summary>\n /// Get the BitmapFrame List.\n /// </summary>\n public List<BitmapFrame> Frames { get; private set; }\n\n /// <summary>\n /// Get or set the repeatBehavior of the animation when source is gif formart.This is a dependency object.\n /// </summary>\n public RepeatBehavior AnimationRepeatBehavior\n {\n get { return (RepeatBehavior)GetValue(AnimationRepeatBehaviorProperty); }\n set { SetValue(AnimationRepeatBehaviorProperty, value); }\n }\n\n public new BitmapImage Source\n {\n get { return (BitmapImage)GetValue(SourceProperty); }\n set { SetValue(SourceProperty, value); }\n }\n\n public Uri UriSource\n {\n get { return (Uri)GetValue(UriSourceProperty); }\n set { SetValue(UriSourceProperty, value); }\n }\n\n #endregion\n\n #region Protected interface\n\n /// <summary> \n /// Provides derived classes an opportunity to handle changes to the Source property. \n /// </summary> \n protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs e)\n {\n ClearAnimation();\n BitmapImage source;\n if (e.NewValue is Uri)\n {\n source = new BitmapImage();\n source.BeginInit();\n source.UriSource = e.NewValue as Uri;\n source.CacheOption = BitmapCacheOption.OnLoad;\n source.EndInit();\n }\n else if (e.NewValue is BitmapImage)\n {\n source = e.NewValue as BitmapImage;\n }\n else\n {\n return;\n }\n BitmapDecoder decoder;\n if (source.StreamSource != null)\n {\n decoder = BitmapDecoder.Create(source.StreamSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);\n }\n else if (source.UriSource != null)\n {\n decoder = BitmapDecoder.Create(source.UriSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);\n }\n else\n {\n return;\n }\n if (decoder.Frames.Count == 1)\n {\n base.Source = decoder.Frames[0];\n return;\n }\n\n this.Frames = decoder.Frames.ToList();\n\n PrepareAnimation();\n }\n\n #endregion\n\n #region Private properties\n\n private Int32Animation Animation { get; set; }\n private bool IsAnimationWorking { get; set; }\n\n #endregion\n\n #region Private methods\n\n private void ClearAnimation()\n {\n if (Animation != null)\n {\n BeginAnimation(FrameIndexProperty, null);\n }\n\n IsAnimationWorking = false;\n Animation = null;\n this.Frames = null;\n }\n\n private void PrepareAnimation()\n {\n Animation =\n new Int32Animation(\n 0,\n this.Frames.Count - 1,\n new Duration(\n new TimeSpan(\n 0,\n 0,\n 0,\n this.Frames.Count / 10,\n (int)((this.Frames.Count / 10.0 - this.Frames.Count / 10) * 1000))))\n {\n RepeatBehavior = RepeatBehavior.Forever\n };\n\n base.Source = this.Frames[0];\n BeginAnimation(FrameIndexProperty, Animation);\n IsAnimationWorking = true;\n }\n\n private static void ChangingFrameIndex\n (DependencyObject dp, DependencyPropertyChangedEventArgs e)\n {\n AnimatedImage animatedImage = dp as AnimatedImage;\n\n if (animatedImage == null || !animatedImage.IsAnimationWorking)\n {\n return;\n }\n\n int frameIndex = (int)e.NewValue;\n ((Image)animatedImage).Source = animatedImage.Frames[frameIndex];\n animatedImage.InvalidateVisual();\n }\n\n /// <summary> \n /// Handles changes to the Source property. \n /// </summary> \n private static void OnSourceChanged\n (DependencyObject dp, DependencyPropertyChangedEventArgs e)\n {\n ((AnimatedImage)dp).OnSourceChanged(e);\n }\n\n #endregion\n\n #region Dependency Properties\n\n /// <summary> \n /// FrameIndex Dependency Property \n /// </summary> \n public static readonly DependencyProperty FrameIndexProperty =\n DependencyProperty.Register(\n \"FrameIndex\",\n typeof(int),\n typeof(AnimatedImage),\n new UIPropertyMetadata(0, ChangingFrameIndex));\n\n /// <summary> \n /// Source Dependency Property \n /// </summary> \n public new static readonly DependencyProperty SourceProperty =\n DependencyProperty.Register(\n \"Source\",\n typeof(BitmapImage),\n typeof(AnimatedImage),\n new FrameworkPropertyMetadata(\n null,\n FrameworkPropertyMetadataOptions.AffectsRender |\n FrameworkPropertyMetadataOptions.AffectsMeasure,\n OnSourceChanged));\n\n /// <summary>\n /// AnimationRepeatBehavior Dependency Property\n /// </summary>\n public static readonly DependencyProperty AnimationRepeatBehaviorProperty =\n DependencyProperty.Register(\n \"AnimationRepeatBehavior\",\n typeof(RepeatBehavior),\n typeof(AnimatedImage),\n new PropertyMetadata(null));\n\n public static readonly DependencyProperty UriSourceProperty =\n DependencyProperty.Register(\n \"UriSource\",\n typeof(Uri),\n typeof(AnimatedImage),\n new FrameworkPropertyMetadata(\n null,\n FrameworkPropertyMetadataOptions.AffectsRender |\n FrameworkPropertyMetadataOptions.AffectsMeasure,\n OnSourceChanged));\n\n #endregion\n}\n"
},
{
"answer_id": 3625400,
"author": "MrPloops",
"author_id": 437737,
"author_profile": "https://Stackoverflow.com/users/437737",
"pm_score": 5,
"selected": false,
"text": "public MainWindow()\n{\n InitializeComponent();\n Files = Directory.GetFiles(@\"I:\\images\");\n this.DataContext= this;\n}\npublic string[] Files\n{get;set;}\n <Window x:Class=\"PicViewer.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\">\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"175\" />\n <ColumnDefinition Width=\"*\" />\n </Grid.ColumnDefinitions>\n <ListBox x:Name=\"lst\" ItemsSource=\"{Binding Path=Files}\"/>\n <MediaElement Grid.Column=\"1\" LoadedBehavior=\"Play\" Source=\"{Binding ElementName=lst, Path=SelectedItem}\" Stretch=\"None\"/>\n </Grid>\n</Window>\n"
},
{
"answer_id": 5519381,
"author": "CodeMouse92",
"author_id": 472647,
"author_profile": "https://Stackoverflow.com/users/472647",
"pm_score": 2,
"selected": false,
"text": "<Image Name=\"Image1\">\n <Image.Triggers>\n <EventTrigger RoutedEvent=\"Image.Loaded\"\n <EventTrigger.Actions>\n <BeginStoryboard>\n <Storyboard>\n <ObjectAnimationUsingKeyFrames Duration=\"0:0:1\" Storyboard.TargetProperty=\"Source\" RepeatBehavior=\"Forever\">\n <DiscreteObjectKeyFrames KeyTime=\"0:0:0\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image1.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n <DiscreteObjectKeyFrames KeyTime=\"0:0:0.25\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image2.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n <DiscreteObjectKeyFrames KeyTime=\"0:0:0.5\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image3.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n <DiscreteObjectKeyFrames KeyTime=\"0:0:0.75\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image4.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n <DiscreteObjectKeyFrames KeyTime=\"0:0:1\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image5.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n </ObjectAnimationUsingKeyFrames>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger.Actions>\n </EventTrigger>\n </Image.Triggers>\n</Image>\n"
},
{
"answer_id": 6525750,
"author": "sondlerd",
"author_id": 329133,
"author_profile": "https://Stackoverflow.com/users/329133",
"pm_score": 2,
"selected": false,
"text": "private void SetupProgressIcon()\n{\n Uri uri = new Uri(\"pack://application:,,,/WPFTest;component/Images/animated_progress_apple.gif\");\n if (uri != null)\n {\n Stream stream = Application.GetContentStream(uri).Stream; \n imgProgressBox.Image = new System.Drawing.Bitmap(stream);\n }\n}\n"
},
{
"answer_id": 6714692,
"author": "Lynn",
"author_id": 369401,
"author_profile": "https://Stackoverflow.com/users/369401",
"pm_score": 3,
"selected": false,
"text": "<WindowsFormsHost x:Name=\"_loadingHost\">\n <Forms:PictureBox x:Name=\"_loadingPictureBox\"/>\n</WindowsFormsHost>\n public partial class ProgressIcon\n{\n public ProgressIcon()\n {\n InitializeComponent();\n var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(\"My.Namespace.ProgressIcon.gif\");\n var image = System.Drawing.Image.FromStream(stream);\n Loaded += (s, e) => _loadingPictureBox.Image = image;\n }\n}\n"
},
{
"answer_id": 11034008,
"author": "Igor Vaschuk",
"author_id": 154664,
"author_profile": "https://Stackoverflow.com/users/154664",
"pm_score": 8,
"selected": false,
"text": "PM> Install-Package WpfAnimatedGif <Window x:Class=\"MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:gif=\"http://wpfanimatedgif.codeplex.com\" <!-- THIS NAMESPACE -->\n Title=\"MainWindow\" Height=\"350\" Width=\"525\">\n\n<Grid>\n <!-- EXAMPLE USAGE BELOW -->\n <Image gif:ImageBehavior.AnimatedSource=\"Images/animated.gif\" />\n <Image gif:ImageBehavior.RepeatBehavior=\"3x\"\n gif:ImageBehavior.AnimatedSource=\"Images/animated.gif\" />\n var image = new BitmapImage();\nimage.BeginInit();\nimage.UriSource = new Uri(fileName);\nimage.EndInit();\nImageBehavior.SetAnimatedSource(img, image);\n"
},
{
"answer_id": 19541853,
"author": "Super AquaMen",
"author_id": 2755349,
"author_profile": "https://Stackoverflow.com/users/2755349",
"pm_score": 0,
"selected": false,
"text": ".gif PictureBox Bitmap ImageAnimator BitmapImage .gif XAML <Window x:Class=\"PlayGifHelp.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\" Loaded=\"MainWindow_Loaded\">\n\n <Grid>\n <Image x:Name=\"SampleImage\" />\n </Grid>\n</Window>\n Code behind public partial class MainWindow : Window\n{\n public MainWindow()\n {\n InitializeComponent();\n }\n\n Bitmap _bitmap;\n BitmapSource _source;\n\n private BitmapSource GetSource()\n {\n if (_bitmap == null)\n {\n string path = Directory.GetCurrentDirectory();\n\n // Check the path to the .gif file\n _bitmap = new Bitmap(path + @\"\\anim.gif\");\n }\n\n IntPtr handle = IntPtr.Zero;\n handle = _bitmap.GetHbitmap();\n\n return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());\n }\n\n private void MainWindow_Loaded(object sender, RoutedEventArgs e)\n {\n _source = GetSource();\n SampleImage.Source = _source;\n ImageAnimator.Animate(_bitmap, OnFrameChanged);\n }\n\n private void FrameUpdatedCallback()\n {\n ImageAnimator.UpdateFrames();\n\n if (_source != null)\n {\n _source.Freeze();\n }\n\n _source = GetSource();\n\n SampleImage.Source = _source;\n InvalidateVisual();\n }\n\n private void OnFrameChanged(object sender, EventArgs e)\n {\n Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(FrameUpdatedCallback));\n }\n}\n Bitmap .gif"
},
{
"answer_id": 20238016,
"author": "Chobits",
"author_id": 2195923,
"author_profile": "https://Stackoverflow.com/users/2195923",
"pm_score": 1,
"selected": false,
"text": " using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text;\n using System.Windows.Controls;\n using System.Windows;\n using System.Windows.Media.Imaging;\n using System.IO;\n using System.Windows.Threading;\n\n namespace IEXM.Components\n {\n public class GifImage : Image\n {\n #region gif Source, such as \"/IEXM;component/Images/Expression/f020.gif\"\n public string GifSource\n {\n get { return (string)GetValue(GifSourceProperty); }\n set { SetValue(GifSourceProperty, value); }\n }\n\n public static readonly DependencyProperty GifSourceProperty =\n DependencyProperty.Register(\"GifSource\", typeof(string),\n typeof(GifImage), new UIPropertyMetadata(null, GifSourcePropertyChanged));\n\n private static void GifSourcePropertyChanged(DependencyObject sender,\n DependencyPropertyChangedEventArgs e)\n {\n (sender as GifImage).Initialize();\n }\n #endregion\n\n #region control the animate\n /// <summary>\n /// Defines whether the animation starts on it's own\n /// </summary>\n public bool IsAutoStart\n {\n get { return (bool)GetValue(AutoStartProperty); }\n set { SetValue(AutoStartProperty, value); }\n }\n\n public static readonly DependencyProperty AutoStartProperty =\n DependencyProperty.Register(\"IsAutoStart\", typeof(bool),\n typeof(GifImage), new UIPropertyMetadata(false, AutoStartPropertyChanged));\n\n private static void AutoStartPropertyChanged(DependencyObject sender,\n DependencyPropertyChangedEventArgs e)\n {\n if ((bool)e.NewValue)\n (sender as GifImage).StartAnimation();\n else\n (sender as GifImage).StopAnimation();\n }\n #endregion\n\n private bool _isInitialized = false;\n private System.Drawing.Bitmap _bitmap;\n private BitmapSource _source;\n\n [System.Runtime.InteropServices.DllImport(\"gdi32.dll\")]\n public static extern bool DeleteObject(IntPtr hObject);\n\n private BitmapSource GetSource()\n {\n if (_bitmap == null)\n {\n _bitmap = new System.Drawing.Bitmap(Application.GetResourceStream(\n new Uri(GifSource, UriKind.RelativeOrAbsolute)).Stream);\n }\n\n IntPtr handle = IntPtr.Zero;\n handle = _bitmap.GetHbitmap();\n\n BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(\n handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());\n DeleteObject(handle);\n return bs;\n }\n\n private void Initialize()\n {\n // Console.WriteLine(\"Init: \" + GifSource);\n if (GifSource != null)\n Source = GetSource();\n _isInitialized = true;\n }\n\n private void FrameUpdatedCallback()\n {\n System.Drawing.ImageAnimator.UpdateFrames();\n\n if (_source != null)\n {\n _source.Freeze();\n }\n\n _source = GetSource();\n\n // Console.WriteLine(\"Working: \" + GifSource);\n\n Source = _source;\n InvalidateVisual();\n }\n\n private void OnFrameChanged(object sender, EventArgs e)\n {\n Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(FrameUpdatedCallback));\n }\n\n /// <summary>\n /// Starts the animation\n /// </summary>\n public void StartAnimation()\n {\n if (!_isInitialized)\n this.Initialize();\n\n\n // Console.WriteLine(\"Start: \" + GifSource);\n\n System.Drawing.ImageAnimator.Animate(_bitmap, OnFrameChanged);\n }\n\n /// <summary>\n /// Stops the animation\n /// </summary>\n public void StopAnimation()\n {\n _isInitialized = false;\n if (_bitmap != null)\n {\n System.Drawing.ImageAnimator.StopAnimate(_bitmap, OnFrameChanged);\n _bitmap.Dispose();\n _bitmap = null;\n }\n _source = null;\n Initialize();\n GC.Collect();\n GC.WaitForFullGCComplete();\n\n // Console.WriteLine(\"Stop: \" + GifSource);\n }\n\n public void Dispose()\n {\n _isInitialized = false;\n if (_bitmap != null)\n {\n System.Drawing.ImageAnimator.StopAnimate(_bitmap, OnFrameChanged);\n _bitmap.Dispose();\n _bitmap = null;\n }\n _source = null;\n GC.Collect();\n GC.WaitForFullGCComplete();\n // Console.WriteLine(\"Dispose: \" + GifSource);\n }\n }\n}\n <localComponents:GifImage x:Name=\"gifImage\" IsAutoStart=\"True\" GifSource=\"{Binding Path=value}\" />\n"
},
{
"answer_id": 20914839,
"author": "Vojta",
"author_id": 3159082,
"author_profile": "https://Stackoverflow.com/users/3159082",
"pm_score": 0,
"selected": false,
"text": "GifImage.Initialize() private void Initialize()\n {\n _gifDecoder = new GifBitmapDecoder(new Uri(\"pack://application:,,,\" + this.GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n\n int duration=0;\n _animation = new Int32AnimationUsingKeyFrames();\n _animation.KeyFrames.Add(new DiscreteInt32KeyFrame(0, KeyTime.FromTimeSpan(new TimeSpan(0))));\n foreach (BitmapFrame frame in _gifDecoder.Frames)\n {\n BitmapMetadata btmd = (BitmapMetadata)frame.Metadata;\n duration += (ushort)btmd.GetQuery(\"/grctlext/Delay\");\n _animation.KeyFrames.Add(new DiscreteInt32KeyFrame(_gifDecoder.Frames.IndexOf(frame)+1, KeyTime.FromTimeSpan(new TimeSpan(duration*100000))));\n } \n _animation.RepeatBehavior = RepeatBehavior.Forever;\n this.Source = _gifDecoder.Frames[0]; \n _isInitialized = true;\n }\n"
},
{
"answer_id": 23245570,
"author": "Pradip Daunde",
"author_id": 2473086,
"author_profile": "https://Stackoverflow.com/users/2473086",
"pm_score": 4,
"selected": false,
"text": "<MediaElement> <MediaElement Height=\"113\" HorizontalAlignment=\"Left\" Margin=\"12,12,0,0\" \nName=\"mediaElement1\" VerticalAlignment=\"Top\" Width=\"198\" Source=\"C:\\Users\\abc.gif\"\nLoadedBehavior=\"Play\" Stretch=\"Fill\" SpeedRatio=\"1\" IsMuted=\"False\" />\n"
},
{
"answer_id": 24368688,
"author": "matuuar",
"author_id": 1472230,
"author_profile": "https://Stackoverflow.com/users/1472230",
"pm_score": 3,
"selected": false,
"text": " PM > Install-Package WpfAnimatedGif\n <Window x:Class=\"WpfAnimatedGif.Demo.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:gif=\"http://wpfanimatedgif.codeplex.com\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\">\n <Grid>\n <Image gif:ImageBehavior.AnimatedSource=\"Images/animated.gif\" />\n ...\n"
},
{
"answer_id": 51128230,
"author": "Heitor Castro",
"author_id": 2386059,
"author_profile": "https://Stackoverflow.com/users/2386059",
"pm_score": 0,
"selected": false,
"text": "ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));\nImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);\n var image = new BitmapImage();\nimage.BeginInit();\nimage.UriSource = new Uri(fileName);\nimage.EndInit();\nImageBehavior.SetAnimatedSource(img, image);\nImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));\nImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);\n"
},
{
"answer_id": 56975966,
"author": "user10763036",
"author_id": 10763036,
"author_profile": "https://Stackoverflow.com/users/10763036",
"pm_score": 0,
"selected": false,
"text": " public async Task GIF_Animation_Pro(string FileName,int speed,bool _Repeat)\n {\n int ab=0;\n var gif = GifBitmapDecoder.Create(new Uri(FileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n var getFrames = gif.Frames;\n BitmapFrame[] frames = getFrames.ToArray();\n await Task.Run(() =>\n {\n\n\n while (ab < getFrames.Count())\n {\n Thread.Sleep(speed);\ntry\n{\n Dispatcher.Invoke(() =>\n {\n gifImage.Source = frames[ab];\n });\n if (ab == getFrames.Count - 1&&_Repeat)\n {\n ab = 0;\n\n }\n ab++;\n }\n catch\n{\n}\n\n }\n });\n }\n public async Task GIF_Animation_Pro(Stream stream, int speed,bool _Repeat)\n {\n int ab = 0; \n var gif = GifBitmapDecoder.Create(stream , BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n var getFrames = gif.Frames;\n BitmapFrame[] frames = getFrames.ToArray();\n await Task.Run(() =>\n {\n\n\n while (ab < getFrames.Count())\n {\n Thread.Sleep(speed);\n try\n {\n\n\n Dispatcher.Invoke(() =>\n {\n gifImage.Source = frames[ab];\n });\n if (ab == getFrames.Count - 1&&_Repeat)\n {\n ab = 0;\n\n }\n ab++;\n }\n catch{} \n\n\n\n }\n });\n }\n"
},
{
"answer_id": 62351761,
"author": "Marcos Kazimoto",
"author_id": 13736405,
"author_profile": "https://Stackoverflow.com/users/13736405",
"pm_score": 2,
"selected": false,
"text": " <ProgressBar Height=\"20\" Width=\"100\" IsIndeterminate=\"True\"/>\n"
},
{
"answer_id": 68041187,
"author": "Kip Morgan",
"author_id": 6058905,
"author_profile": "https://Stackoverflow.com/users/6058905",
"pm_score": 1,
"selected": false,
"text": "<WebBrowser Source=\"https://media.giphy.com/media/Ent2j55lyQipa/giphy.gif\" />\n <WebBrowser x:Name=\"WebBrowser\" />\n private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n string curDir = Directory.GetCurrentDirectory();\n this.WebBrowser.Source = new Uri(String.Format(\"file:///{0}/10-monkey.gif\", curDir));\n}\n"
},
{
"answer_id": 73124090,
"author": "Bimo",
"author_id": 5632412,
"author_profile": "https://Stackoverflow.com/users/5632412",
"pm_score": 0,
"selected": false,
"text": " <WebBrowser Name=\"webBrowser1\"/>\n webBrowser1.NavigateToString( \n @\"<img src=\"\"arrow-24.png\"\"/>\"\n );\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2522462/"
] |
210,936
|
<p>Having an issue with some images using IE7 - work fine in 6 and in all versions of Firefox.</p>
<p>Has anyone run across this before? I know I've had it happen in the past (and I googled a fix, but darned if I can find the fix again... note to self, document things like this for future ;) )</p>
<pre><code><div class="contextBlock">
<p class="cntImg"><a href="files/image.jsp" title="Image"><img src="files/images/image.jpg" alt="Image" width="171" height="96" border="0">Image</a></p>
<p class="cntImg"><a href="files/image2.jsp" title="image2"><img src="files/images/image2.jpg" alt="Image2" width="171" height="96" border="0">Image2 </a></p>
<p class="comment">Click to enlarge</p>
<div class="clr"></div>
</code></pre>
<p></p>
|
[
{
"answer_id": 211028,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 2,
"selected": false,
"text": "<a href=\"files/image.jsp\" title=\"Image\">\n <img src=\"files/images/image.jpg\" alt=\"Image\" width=\"171\" height=\"96\" border=\"0\" />\n</a>\n"
},
{
"answer_id": 211308,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "contextBlock cntImg clr"
},
{
"answer_id": 8381466,
"author": "bgcode",
"author_id": 1080979,
"author_profile": "https://Stackoverflow.com/users/1080979",
"pm_score": 1,
"selected": false,
"text": "identify -verbose MattCutts.jpg | grep Colorspace mogrify -colorspace rgb MattCutts.jpg"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,939
|
<p>I've been developing a GUI library for Windows (as a personal side project, no aspirations of usefulness). For my main window class, I've set up a hierarchy of option classes (using the <a href="http://www.parashift.com/c++-faq-lite/named-parameter-idiom.html" rel="nofollow noreferrer">Named Parameter Idiom</a>), because some options are shared and others are specific to particular types of windows (like dialogs).</p>
<p>The way the Named Parameter Idiom works, the functions of the parameter class have to return the object they're called on. The problem is that, in the hierarchy, each one has to be a <em>different</em> class -- the <code>createWindowOpts</code> class for standard windows, the <code>createDialogOpts</code> class for dialogs, and the like. I've dealt with that by making all the option classes templates. Here's an example:</p>
<pre><code>template <class T>
class _sharedWindowOpts: public detail::_baseCreateWindowOpts {
public: ///////////////////////////////////////////////////////////////
// No required parameters in this case.
_sharedWindowOpts() { };
typedef T optType;
// Commonly used options
optType& at(int x, int y) { mX=x; mY=y; return static_cast<optType&>(*this); }; // Where to put the upper-left corner of the window; if not specified, the system sets it to a default position
optType& at(int x, int y, int width, int height) { mX=x; mY=y; mWidth=width; mHeight=height; return static_cast<optType&>(*this); }; // Sets the position and size of the window in a single call
optType& background(HBRUSH b) { mBackground=b; return static_cast<optType&>(*this); }; // Sets the default background to this brush
optType& background(INT_PTR b) { mBackground=HBRUSH(b+1); return static_cast<optType&>(*this); }; // Sets the default background to one of the COLOR_* colors; defaults to COLOR_WINDOW
optType& cursor(HCURSOR c) { mCursor=c; return static_cast<optType&>(*this); }; // Sets the default mouse cursor for this window; defaults to the standard arrow
optType& hidden() { mStyle&=~WS_VISIBLE; return static_cast<optType&>(*this); }; // Windows are visible by default
optType& icon(HICON iconLarge, HICON iconSmall=0) { mIcon=iconLarge; mSmallIcon=iconSmall; return static_cast<optType&>(*this); }; // Specifies the icon, and optionally a small icon
// ...Many others removed...
};
template <class T>
class _createWindowOpts: public _sharedWindowOpts<T> {
public: ///////////////////////////////////////////////////////////////
_createWindowOpts() { };
// These can't be used with child windows, or aren't needed
optType& menu(HMENU m) { mMenuOrId=m; return static_cast<optType&>(*this); }; // Gives the window a menu
optType& owner(HWND hwnd) { mParentOrOwner=hwnd; return static_cast<optType&>(*this); }; // Sets the optional parent/owner
};
class createWindowOpts: public _createWindowOpts<createWindowOpts> {
public: ///////////////////////////////////////////////////////////////
createWindowOpts() { };
};
</code></pre>
<p>It works, but as you can see, it requires a noticeable amount of extra work: a type-cast on the return type for each function, extra template classes, etcetera.</p>
<p>My question is, is there an easier way to implement the Named Parameter Idiom in this case, one that doesn't require all the extra stuff?</p>
|
[
{
"answer_id": 211106,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": 1,
"selected": false,
"text": "class sharedWindowOpts\n{\npublic:\n\n sharedWindowOpts() {};\n\n // Commonly used options\n template <class optType>\n static optType& at(int x, int y, optType& opts) { opts.mX=x; opts.mY=y; return opts; };\n\n template <class optType>\n static optType& background(HBRUSH b, optType& opts) { opts.mBackground=b; return opts; };\n\n // etc...\n}\n\nclass createWindowOpts : public sharedWindowOpts\n{\npublic:\n createWindowOpts() : sharedwindowOpts() {};\n\n // These can't be used with child windows, or aren't needed\n template <class optType>\n static optType& menu(HMENU m, optType& opts) { opts.mMenuOrId=m; return opts; };\n\n template <class optType>\n static optType& owner(HWND hwnd, optType& opts) { opts.mParentOrOwner=hwnd; return opts; };\n }\n CreateWindow( createWindowOpts::owner(hwnd,\n createWindowOpts::at(0, 100, // can use createWindowOpts because it doesn't hide sharedWindowsOpts::at\n createWindowOpts::menu(hmenu, createWindowOpts() ) ) ) );\n"
},
{
"answer_id": 211624,
"author": "Pyry Jahkola",
"author_id": 26981,
"author_profile": "https://Stackoverflow.com/users/26981",
"pm_score": 3,
"selected": false,
"text": "template <class T>\nclass _sharedWindowOpts: public detail::_baseCreateWindowOpts {\n\nprotected: // (protected so the inheriting classes may also use it)\n\n T & me() { return static_cast<T&>(*this); } // !\n\npublic:\n // No required parameters in this case.\n _sharedWindowOpts() { };\n\n typedef T optType;\n\n // Commonly used options\n optType& at(int x, int y) { mX=x; mY=y; return me(); }; // !\n // ...\n};\n"
},
{
"answer_id": 2807405,
"author": "Kyle",
"author_id": 285883,
"author_profile": "https://Stackoverflow.com/users/285883",
"pm_score": 0,
"selected": false,
"text": "//////// Base.. \n\ntemplate<typename DerivedBuilder, typename Options>\nclass Builder\n{\nprotected:\n Builder() {}\n DerivedBuilder& me() { return *static_cast<DerivedBuilder*>(this); }\n\n Options options;\n};\n\n\n////////////////////////// A //////////////////////////\n\n\nclass Options_A\n{\npublic:\n Options_A() : a(7) {}\n int a;\n};\n\nclass Builder_A;\n\nclass A \n{\npublic:\n virtual ~A() {}\n virtual void print() { cout << \"Class A, a:\" << a << endl; }\n\nprotected:\n friend class Builder_A;\n A(const Options_A& options) : a(options.a) {}\n int a;\n};\n\n\n\ntemplate<typename DerivedBuilder, typename Options = Options_A>\nclass BuilderT_A : public Builder<DerivedBuilder, Options>\n{\npublic:\n using Builder<DerivedBuilder, Options>::options;\n using Builder<DerivedBuilder, Options>::me;\n DerivedBuilder& a(int p) { options.a = p; return me(); }\n};\n\n\nclass Builder_A : public BuilderT_A<Builder_A>\n{\npublic:\n shared_ptr<A> create()\n {\n shared_ptr<A> obj(new A(options));\n return obj;\n }\n};\n\n////////////////////////// B //////////////////////////\n\n\n\nclass Options_B : public Options_A\n{\npublic:\n Options_B() : b(8) {}\n int b;\n};\n\nclass Builder_B;\n\nclass B : public A \n{\npublic:\n virtual ~B() {}\n virtual void print() { cout << \"Class B, a:\" << a << \", b:\" << b << endl; }\n\nprotected:\n friend class Builder_B;\n B(const Options_B& options) : A(options), b(options.b) {}\n int b;\n};\n\n\ntemplate<typename DerivedBuilder, typename Options = Options_B>\nclass BuilderT_B : public BuilderT_A<DerivedBuilder, Options>\n{\npublic:\n using Builder<DerivedBuilder, Options>::options;\n using Builder<DerivedBuilder, Options>::me;\n DerivedBuilder& b(int p) { options.b = p; return me(); }\n};\n\n\nclass Builder_B : public BuilderT_B<Builder_B>\n{\npublic:\n shared_ptr<B> create()\n {\n shared_ptr<B> obj(new B(options));\n return obj;\n }\n};\n\n\n\n////////////////////////// C //////////////////////////\n\n\n\nclass Options_C : public Options_B\n{\npublic:\n Options_C() : c(9) {}\n int c;\n};\n\nclass Builder_C;\n\nclass C : public B \n{\npublic:\n virtual ~C() {}\n virtual void print() { cout << \"Class C, a:\" << a << \", b:\" << b << \", c:\" << c << endl; }\n\nprotected:\n friend class Builder_C;\n C(const Options_C& options) : B(options), c(options.c) {}\n int c;\n};\n\n\ntemplate<typename DerivedBuilder, typename Options = Options_C>\nclass BuilderT_C : public BuilderT_B<DerivedBuilder, Options_C>\n{\npublic:\n using Builder<DerivedBuilder, Options>::options;\n using Builder<DerivedBuilder, Options>::me;\n DerivedBuilder& c(int p) { options.c = p; return *static_cast<DerivedBuilder*>(this); }\n};\n\n\nclass Builder_C : public BuilderT_C<Builder_C>\n{\npublic:\n shared_ptr<C> create()\n {\n shared_ptr<C> obj(new C(options));\n return obj;\n }\n};\n\n\n\n\n\n///////////////////////////////////////////////////////////////////////////\n\n\nint main()\n{\n shared_ptr<A> a = Builder_A().a(55).a(1).create();\n a->print();\n\n shared_ptr<B> b = Builder_B().b(99).b(2).a(88).b(4).a(2).b(3).create();\n b->print();\n\n shared_ptr<C> c = Builder_C().a(99).b(98).c(97).a(96).c(6).b(5).a(4).create();\n c->print();\n\n return 0;\n}\n\n/* Output:\n\nClass A, a:1\nClass B, a:2, b:3\nClass C, a:4, b:5, c:6\n\n*/\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
210,945
|
<p>I have seen many examples, with many 'no, you missed something' comments. What is the right way to match an e-mail address?</p>
<p>For Sanity sake, only fully-qualified domain names, no @localhost allowed. (or, both ways)</p>
<p>Subdomains must be allowed (issac@deptartment.company.museum)</p>
|
[
{
"answer_id": 212008,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "([a-zA-Z0-9_\\-])([a-zA-Z0-9_\\-\\.]*)@(\\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}|((([a-zA-Z0-9\\-]+)\\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\])\n"
},
{
"answer_id": 647647,
"author": "porges",
"author_id": 10311,
"author_profile": "https://Stackoverflow.com/users/10311",
"pm_score": 3,
"selected": false,
"text": "'\\0'"
},
{
"answer_id": 1682659,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 2,
"selected": false,
"text": "[a-z]/i \\w ([^.@]+)(\\\\.[^.@]+)*@([^.@]+\\\\.)+([^.@]+)\n"
},
{
"answer_id": 1804103,
"author": "Rob",
"author_id": 203452,
"author_profile": "https://Stackoverflow.com/users/203452",
"pm_score": 2,
"selected": false,
"text": "(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\n\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(\n?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \n\\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\0\n31]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\\n](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+\n(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:\n(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)\n?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\\nr\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[\n \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)\n?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t]\n)*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[\n \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*\n)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)\n*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+\n|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\n\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\n\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t\n]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031\n]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](\n?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?\n:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?\n:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?\n:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?\n[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\n\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>\n@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"\n(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?\n:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\n\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\n\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(\n?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;\n:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([\n^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"\n.\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\\n]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\\n[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\\nr\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]\n|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\0\n00-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\\n.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,\n;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?\n:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[\n^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]\n]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(\n?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(\n?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\n\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t\n])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t\n])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?\n:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\n\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:\n[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\\n]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)\n?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"\n()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)\n?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>\n@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[\n \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,\n;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\n\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\n\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])\n*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])\n+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\\n.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(\n?:\\r\\n)?[ \\t])*))*)?;\\s*)\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
] |
210,975
|
<p>Looking for an example in linq about how to insert a row of a gridview into datacontext. </p>
|
[
{
"answer_id": 212008,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "([a-zA-Z0-9_\\-])([a-zA-Z0-9_\\-\\.]*)@(\\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}|((([a-zA-Z0-9\\-]+)\\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\])\n"
},
{
"answer_id": 647647,
"author": "porges",
"author_id": 10311,
"author_profile": "https://Stackoverflow.com/users/10311",
"pm_score": 3,
"selected": false,
"text": "'\\0'"
},
{
"answer_id": 1682659,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 2,
"selected": false,
"text": "[a-z]/i \\w ([^.@]+)(\\\\.[^.@]+)*@([^.@]+\\\\.)+([^.@]+)\n"
},
{
"answer_id": 1804103,
"author": "Rob",
"author_id": 203452,
"author_profile": "https://Stackoverflow.com/users/203452",
"pm_score": 2,
"selected": false,
"text": "(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\n\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(\n?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \n\\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\0\n31]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\\n](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+\n(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:\n(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)\n?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\\nr\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[\n \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)\n?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t]\n)*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[\n \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*\n)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)\n*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+\n|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\n\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\n\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t\n]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031\n]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](\n?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?\n:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?\n:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?\n:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?\n[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\n\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>\n@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"\n(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?\n:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\n\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\n\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(\n?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;\n:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([\n^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"\n.\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\\n]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\\n[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\\nr\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]\n|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\0\n00-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\\n.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,\n;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?\n:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[\n^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]\n]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(\n?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(\n?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\n\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t\n])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t\n])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?\n:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\n\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:\n[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\\n]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)\n?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"\n()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)\n?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>\n@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[\n \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,\n;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\n\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\n\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])\n*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])\n+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\\n.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(\n?:\\r\\n)?[ \\t])*))*)?;\\s*)\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
210,978
|
<p>I have a question about using <code>os.execvp</code> in Python. I have the following bit of code that's used to create a list of arguments:</p>
<pre>
args = [ "java"
, classpath
, "-Djava.library.path=" + lib_path()
, ea
, "-Xmx1000m"
, "-server"
, "code_swarm"
, params
]
</pre>
<p>When I output a string using <code>" ".join(args)</code> and paste that into my shell prompt, the JVM launches fine, and everything works. Everything works if I use <code>os.system(" ".join(args))</code> in my Python script, too.</p>
<p><em>But</em> the following bit of code does not work:</p>
<pre>os.execvp("java", args)</pre>
<p>I get the following error:</p>
<pre>
Unrecognized option: -classpath [and then the classpath I created, which looks okay]
Could not create the Java virtual machine.
</pre>
<p>So what gives? Why does copying/pasting into the shell or using <code>os.system()</code> work, but not <code>os.execvp()</code>?</p>
|
[
{
"answer_id": 210982,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 5,
"selected": true,
"text": "#!/usr/bin/python\nimport sys\nprint sys.argv\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28804/"
] |
210,985
|
<p>I'm doing some optimising for my site and am trying to figure out just how big some inline code can be before it can justify having it's own file instead of being written inline.</p>
<p>My guess on how to measure it would be that the amount of code (CSS or JS in this case) would need to be bigger than the HTTP packets sent and received to get a 304 response. </p>
<p>Please ignore the fact that it's a good practice to keep styles and javascript out of the HTML page and think only in terms of browser performance. :)</p>
|
[
{
"answer_id": 217491,
"author": "mjallday",
"author_id": 6084,
"author_profile": "https://Stackoverflow.com/users/6084",
"pm_score": 0,
"selected": false,
"text": "HTTP/1.1 304 Not Modified\nCache-Control: max-age=604800, public\nLast-Modified: Tue, 17 Jun 2008 17:20:41 GMT\nDate: Mon, 20 Oct 2008 03:49:58 GMT\nServer: ucfe\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084/"
] |
210,986
|
<p>Newbie question...</p>
<p>If I have a file that is in the root of the web app. How do I programmaticaly query the path of that file? ie, what directory it is in?</p>
|
[
{
"answer_id": 210993,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "System.Web.HttpServerUtility.MapPath( \"~/filename.ext\" );\n System.Web.Hosting.VirtualPathUtility.ToAbsolute( \"~/filename.ext\" );\n"
},
{
"answer_id": 211119,
"author": "Jason Whitehorn",
"author_id": 27860,
"author_profile": "https://Stackoverflow.com/users/27860",
"pm_score": 0,
"selected": false,
"text": "<%= Page.ResolveUrl(\"~/PathFromRoot/YourFile.pdf\") %>\n"
},
{
"answer_id": 11439050,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "MapPath HttpServerUtility Controller Server var appRoot = Server.MapPath(\"~/\");\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10431/"
] |
210,996
|
<p>In spring you can initialize a bean by having the applicationContext.xml invoke a constructor, or you can set properties on the bean. What are the trade offs between the two approaches? Is it better to have a constructor (which enforces the contract of having everything it needs in one method) or is it better to have all properties (which gives you flexibility to only inject selectively for example when unit testing.)</p>
<p>What are the trade offs (between writing a bean that uses a constructor to establish it's initial state, or using properties and perhaps an afterProperties() method) ?</p>
|
[
{
"answer_id": 211112,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 2,
"selected": false,
"text": "@PostConstruct afterProperties() afterPropertiesSet() <bean>"
},
{
"answer_id": 211141,
"author": "lycono",
"author_id": 28789,
"author_profile": "https://Stackoverflow.com/users/28789",
"pm_score": 5,
"selected": true,
"text": "public class Person {\n public Person(String name) { ... }\n public Person(String name, String phone) { ... }\n public Person(String name, String phone, String email) { ... }\n}\n"
},
{
"answer_id": 211513,
"author": "Jaap Coomans",
"author_id": 26066,
"author_profile": "https://Stackoverflow.com/users/26066",
"pm_score": 2,
"selected": false,
"text": "public class MyPersonBean {\n @Autowired\n private PersonManager personManager;\n\n public void doSomething() {\n this.personManager.doSomething();\n }\n}\n <context:annotation-config/>\n"
},
{
"answer_id": 469687,
"author": "kukudas",
"author_id": 48402,
"author_profile": "https://Stackoverflow.com/users/48402",
"pm_score": 0,
"selected": false,
"text": "@Resource @Autowired @Qualifier"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6580/"
] |
210,998
|
<p>I am attempting to insert a Canvas3D object inside a Swing JPanel, but the code doesn't seem to be working (i.e. nothing happens):</p>
<pre>
Canvas3D canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
SimpleUniverse universe = new SimpleUniverse(canvas);
BranchGroup root = new BranchGroup();
root.addChild(new ColorCube());
universe.addBranchGraph(root);
universe.getViewingPlatform().setNominalViewingTransform();
canvasPanel.add(canvas);
</pre>
<p>What am I missing? The JPanel was created using NetBean's Visual Editor.</p>
|
[
{
"answer_id": 211131,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 3,
"selected": true,
"text": "canvasPanel.setLayout(new BorderLayout());\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23845/"
] |
211,001
|
<p>In a normal web app w/ login and secure data, what is an easy way to secure that data and prevent it from being seen by using the browser's back button, once a user logs out? </p>
|
[
{
"answer_id": 211079,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 4,
"selected": true,
"text": " Cache-Control: no-cache\n Expires: Fri, 31 Dec 1998 12:00:00 GMT\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444/"
] |
211,008
|
<p>How can I detect in C# whether two files are absolutely identical (size, content, etc.)?</p>
|
[
{
"answer_id": 211042,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 5,
"selected": false,
"text": "static bool FilesAreEqual( string f1, string f2 )\n{\n // get file length and make sure lengths are identical\n long length = new FileInfo( f1 ).Length;\n if( length != new FileInfo( f2 ).Length )\n return false;\n\n // open both for reading\n using( FileStream stream1 = File.OpenRead( f1 ) )\n using( FileStream stream2 = File.OpenRead( f2 ) )\n {\n // compare content for equality\n int b1, b2;\n while( length-- > 0 )\n {\n b1 = stream1.ReadByte();\n b2 = stream2.ReadByte();\n if( b1 != b2 )\n return false;\n }\n }\n\n return true;\n}\n static bool FilesAreEqualFaster( string f1, string f2 )\n{\n // get file length and make sure lengths are identical\n long length = new FileInfo( f1 ).Length;\n if( length != new FileInfo( f2 ).Length )\n return false;\n\n byte[] buf1 = new byte[4096];\n byte[] buf2 = new byte[4096];\n\n // open both for reading\n using( FileStream stream1 = File.OpenRead( f1 ) )\n using( FileStream stream2 = File.OpenRead( f2 ) )\n {\n // compare content for equality\n int b1, b2;\n while( length > 0 )\n {\n // figure out how much to read\n int toRead = buf1.Length;\n if( toRead > length )\n toRead = (int)length;\n length -= toRead;\n\n // read a chunk from each and compare\n b1 = stream1.Read( buf1, 0, toRead );\n b2 = stream2.Read( buf2, 0, toRead );\n for( int i = 0; i < toRead; ++i )\n if( buf1[i] != buf2[i] )\n return false;\n }\n }\n\n return true;\n}\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
211,025
|
<p>I have been maintaining <a href="http://github.com/Pistos/watir-mirror" rel="noreferrer">the git mirror</a> of <a href="http://wtr.rubyforge.org/" rel="noreferrer">the watir project</a>. Some time a couple weeks ago, we had someone ready to submit their first git-based patch. Unfortunately, we ran into some issues regarding line endings (CRLF vs. LF, etc.) because of the multi-platform nature of the project.</p>
<p>I tried what I could to set <a href="http://git-scm.com/docs/gitattributes" rel="noreferrer">the autocrlf option</a> (to 'input'), and do some --hard resets. However, a few days later, the daily update (git svn rebase) is spewing this error:</p>
<pre><code>Incomplete data: Delta source ended unexpectedly
</code></pre>
<p>I've tried googling around for what to do, but even removing the autocrlf setting in the .git/config hasn't helped. I fear the working copy is corrupt, but I hope it is not unrecoverable.</p>
<p>Obviously, a possible course of action is to just re-import from svn and start a fresh mirror, but I hope we don't have to do that, since the current watir-mirror has already been forked, and people have developed new code in their forks.</p>
<p>Thanks in advance for any help.</p>
|
[
{
"answer_id": 4938148,
"author": "Todd Wagner",
"author_id": 608775,
"author_profile": "https://Stackoverflow.com/users/608775",
"pm_score": 4,
"selected": false,
"text": "git svn reset --r XXXXX git svn find-rev XXXXX git svn reset -r XXXXX"
},
{
"answer_id": 16592981,
"author": "Don Branson",
"author_id": 56076,
"author_profile": "https://Stackoverflow.com/users/56076",
"pm_score": 2,
"selected": false,
"text": "git svn fetch git svn fetch --ignore-paths=\"/branches/\" git svn fetch"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28558/"
] |
211,034
|
<p>I'm working on a small UML editor project, in Java, that I started a couple of months ago. After a few weeks, I got a working copy for a UML class diagram editor.</p>
<p>But now, I'm redesigning it completely to support other types of diagrams, such a sequence, state, class, etc. This is done by implementing a graph construction framework (I'm greatly inspired by Cay Horstmann work on the subject with the Violet UML editor).</p>
<p>Redesign was going smoothly until one of my friends told me that I forgot to add a Do/Undo functionnality to the project, which, in my opinion, is vital.</p>
<p>Remembering object oriented design courses, I immediately thought of Memento and Command pattern.</p>
<p>Here's the deal. I have a abstract class, AbstractDiagram, that contains two ArrayLists : one for storing nodes (called Elements in my project) and the other for storing Edges (called Links in my projects). The diagram will probably keep a stack of commands that can be Undoed/Redoed. Pretty standard.</p>
<p>How can I execute these commands in a efficient way? Say, for example, that I want to move a node (the node will be an interface type named INode, and there will be concrete nodes derived from it (ClassNode, InterfaceNode, NoteNode, etc.)). </p>
<p>The position information is held as an attribute in the node, so by modying that attribute in the node itself, the state is changed. When the display will be refreshed, the node will have moved. This is the Memento part of the pattern (I think), with the difference that the object is the state itself.</p>
<p>Moreover, if I keep a clone of the original node (before it moved), I can get back to its old version. The same technique applies for the information contained in the node (the class or interface name, the text for a note node, the attributes name, and so on).</p>
<p>The thing is, how do I replace, in the diagram, the node with its clone upon undo/redo operation? If I clone the original object that is referenced by the diagram (being in the node list), the clone isn't reference in the diagram, and the only thing that points to is the Command itself! Shoud I include mechanisms in the diagram for finding a node according to an ID (for example) so I can replace, in the diagram, the node by its clone (and vice-versa) ? Is it up to the Memento and Command patterns to do that ? What about links? They should be movable too but I don't want to create a command just for links (and one just for nodes), and I should be able to modify the right list (nodes or links) according to the type of the object the command is referring to.</p>
<p>How would you proceed? In short, I am having trouble representing the state of an object in a command/memento pattern so that it can be efficiently recovered and the original object restored in the diagram list, and depending on the object type (node or link).</p>
<p>Thanks a lot!</p>
<p>Guillaume.</p>
<p>P.S.: if I'm not clear, tell me and I will clarify my message (as always!).</p>
<p><strong>Edit</strong></p>
<p>Here's my actual solution, that I started implementing before posting this question.</p>
<p>First, I have an AbstractCommand class defined as follow :</p>
<pre><code>public abstract class AbstractCommand {
public boolean blnComplete;
public void setComplete(boolean complete) {
this.blnComplete = complete;
}
public boolean isComplete() {
return this.blnComplete;
}
public abstract void execute();
public abstract void unexecute();
}
</code></pre>
<p>Then, each type of command is implemented using a concrete derivation of AbstractCommand.</p>
<p>So I have a command to move an object :</p>
<pre><code>public class MoveCommand extends AbstractCommand {
Moveable movingObject;
Point2D startPos;
Point2D endPos;
public MoveCommand(Point2D start) {
this.startPos = start;
}
public void execute() {
if(this.movingObject != null && this.endPos != null)
this.movingObject.moveTo(this.endPos);
}
public void unexecute() {
if(this.movingObject != null && this.startPos != null)
this.movingObject.moveTo(this.startPos);
}
public void setStart(Point2D start) {
this.startPos = start;
}
public void setEnd(Point2D end) {
this.endPos = end;
}
}
</code></pre>
<p>I also have a MoveRemoveCommand (to... move or remove an object/node). If I use the ID of instanceof method, I don't have to pass the diagram to the actual node or link so that it can remove itself from the diagram (which is a bad idea I think).</p>
<p>AbstractDiagram diagram;
Addable obj;
AddRemoveType type;</p>
<pre><code>@SuppressWarnings("unused")
private AddRemoveCommand() {}
public AddRemoveCommand(AbstractDiagram diagram, Addable obj, AddRemoveType type) {
this.diagram = diagram;
this.obj = obj;
this.type = type;
}
public void execute() {
if(obj != null && diagram != null) {
switch(type) {
case ADD:
this.obj.addToDiagram(diagram);
break;
case REMOVE:
this.obj.removeFromDiagram(diagram);
break;
}
}
}
public void unexecute() {
if(obj != null && diagram != null) {
switch(type) {
case ADD:
this.obj.removeFromDiagram(diagram);
break;
case REMOVE:
this.obj.addToDiagram(diagram);
break;
}
}
}
</code></pre>
<p>Finally, I have a ModificationCommand which is used to modify the info of a node or link (class name, etc.). This may be merged in the future with the MoveCommand. This class is empty for now. I will probably do the ID thing with a mechanism to determine if the modified object is a node or an edge (via instanceof or a special denotion in the ID).</p>
<p>Is this is a good solution?</p>
|
[
{
"answer_id": 211105,
"author": "Justin Bozonier",
"author_id": 9401,
"author_profile": "https://Stackoverflow.com/users/9401",
"pm_score": 3,
"selected": true,
"text": "{ width:100, height:50, position:(10,25), content:\"Am I certain?\", edge-connections:null}\n DiagramController\n{\n public DiagramController(diagramBuilder:DiagramBuilder)\n {\n this._diagramBuilder = diagramBuilder;\n this._commandStack = new Stack();\n }\n\n public void Add(node:ConditionalNode)\n {\n this._commandStack.push(node);\n this._diagramBuilder.Draw(node);\n }\n\n public void Undo()\n {\n var node = this._commandStack.pop();\n this._diagramBuilderUndraw(node);\n }\n}\n DiagramController\n{\n public DiagramController(diagramBuilder:DiagramBuilder)\n {\n this._diagramBuilder = diagramBuilder;\n this._commandStack = new Stack();\n }\n\n public void Add(node:ConditionalNode)\n {\n string graphicalRefId = this._diagramBuilder.Draw(node);\n var nodePair = new KeyValuePair<string, ConditionalNode> (graphicalRefId, node);\n this._commandStack.push(nodePair);\n }\n\n public void Undo()\n {\n var nodePair = this._commandStack.pop();\n this._diagramBuilderUndraw(nodePair.Key);\n }\n} \n"
},
{
"answer_id": 5860868,
"author": "Programmer in Paradise",
"author_id": 205483,
"author_profile": "https://Stackoverflow.com/users/205483",
"pm_score": 1,
"selected": false,
"text": "public class NodePositionChangeCommand {\n // This command will act upon this node\n private Node node;\n\n // Old state is stored here\n private NodePositionMemento previousNodePosition;\n\n NodePositionChangeCommand(Node node) {\n this.node = node;\n }\n\n public void execute(NodePositionMemento newPosition) {\n // Save current state in memento object previousNodePosition\n\n // Act upon this.node\n }\n\n public void undo() {\n // Update this.node object with values from this.previousNodePosition\n }\n}\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10687/"
] |
211,035
|
<p>Today is officially my first day with C++ :P</p>
<p>I've downloaded Visual C++ 2005 Express Edition and Microsoft Platform SDK for Windows Server 2003 SP1, because I want to get my hands on the open source <a href="http://code.google.com/p/enso" rel="nofollow noreferrer">Enso Project</a>. </p>
<p>So, after installing scons I went to the console and tried to compile it using scons, but I got this error: </p>
<pre><code>C:\oreyes\apps\enso\enso-read-only\src\platform\win32\Include\WinSdk.h(64) : fatal error C1083: Cannot open include file: 'Windows.h': No such file or directory
scons: *** [src\platform\win32\InputManager\AsyncEventProcessorRegistry.obj] Error 2
scons: building terminated because of errors.
</code></pre>
<p>After checking these links:</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1135164&SiteID=1" rel="nofollow noreferrer">VS ans PSDK</a></p>
<p><a href="https://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffioh-no-such-file-or-directory-vc#160957">Include tiffi.h</a></p>
<p><a href="https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory#81226">Wndows.h</a></p>
<p>I've managed to configure my installation like this:</p>
<p><img src="https://i.stack.imgur.com/z41N8.png" alt="alt text"></p>
<p>And even run this script </p>
<p><img src="https://i.stack.imgur.com/1rB1L.png" alt="alt text"></p>
<p>And I managed to compile the file below in the IDE.</p>
<pre><code>// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
</code></pre>
<p>But I still get that exception in the console. Does anyone have scons experience?</p>
<p><strong>EDIT</strong></p>
<p>Actually (and I forgot to tell you this) I started the command prompt with the link "Visual Studio 2005 Command Prompt".</p>
<p>I assume this will include the paths in environment variables. Well after printing them I find that it didn't:</p>
<pre><code> echo %INCLUDE%
echo %LIB%
echo %PATH%
</code></pre>
<p>And they were not present, so I created this .bat file:</p>
<pre><code>set PATH=%PATH%;"C:\Program Files\Microsoft Platform SDK\Bin"
set INCLUDE=%INCLUDE%;"C:\ Program Files\Microsoft Platform SDK\Include"
set LIB=%LIB%;"C:\ Program Files\Microsoft Platform SDK\Lib"
</code></pre>
<p>Still, scons seeems not to take the vars... :( </p>
|
[
{
"answer_id": 211117,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "vsvars32.bat vcvars32.bat"
},
{
"answer_id": 211164,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 2,
"selected": false,
"text": "c:\\Program Files\\Microsoft Visual Studio 8\\Common7\\Tools\\vsvars32.bat\n cmd.exe /K \"c:\\Program Files\\Microsoft Visual Studio 8\\Common7\\Tools\\vsvars32.bat\"\n"
},
{
"answer_id": 310001,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "import os\nenv = Environment(ENV={'PATH': os.environ['PATH']})\n\nenv['ENV']['TMP'] = os.environ['TMP']\nenv.AppendUnique(CPPPATH=os.environ['INCLUDE'].split(';'))\nenv.AppendUnique(LIBPATH=os.environ['LIB'].split(';'))\n"
},
{
"answer_id": 528160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "REM Fix Error error C1083 'windows.h'\n set PDSKWIN=C:\\Program Files\\Microsoft Platform SDK for Windows Server 2003 R2\n set INCLUDE=%PDSKWIN%\\Include;%INCLUDE%\n\nset LIB=%PDSKWIN%\\Lib;%LIB%\n /useenv vcbuild /useenv /nohtmllog /nologo name.proj (or any file to compile)\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
211,037
|
<p>Similar question as <a href="https://stackoverflow.com/questions/56722/automated-processing-of-an-email-in-java">this one</a> but for a Microsoft Environment.</p>
<p>Email --> Exchange Server -->[something]</p>
<p>For the [something] I was using Outlook 2003 & C# but it <em>feels</em> messy (A program is trying to access outlook, this could be a virus etc)</p>
<pre><code>Microsoft.Office.Interop.Outlook.Application objOutlook = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace objNS = objOutlook.GetNamespace("MAPI");
objNS.Logon("MAPIProfile", "MAPIPassword", false, true);
</code></pre>
<p>Is this the best way to do it? Is there a better way of retrieving and processing emails in a Microsoft environment???</p>
|
[
{
"answer_id": 1808996,
"author": "Pawel Lesnikowski",
"author_id": 80894,
"author_profile": "https://Stackoverflow.com/users/80894",
"pm_score": 1,
"selected": false,
"text": "using(Imap imap = new Imap())\n{\n imap.Connect(\"imap.company.com\");\n imap.UseBestLogin(\"user\", \"password\");\n\n imap.SelectInbox();\n List<long> uids = imap.Search(Flag.Unseen);\n foreach (long uid in uids)\n {\n var eml = imap.GetMessageByUID(uid);\n IMail message = new MailBuilder()\n .CreateFromEml(eml);\n\n Console.WriteLine(message.Subject);\n Console.WriteLine(message.Text); \n }\n imap.Close(true);\n}\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5188/"
] |
211,041
|
<p>Should I be writing Doc Comments for all of my java methods? </p>
|
[
{
"answer_id": 211060,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 7,
"selected": true,
"text": "/** \n * Get the current value of the foo property.\n * The foo property controls the initial guess used by the bla algorithm in\n * {@link #bla}\n * @return The initial guess used by {@link #bla}\n */\nint getFoo() {\n return foo;\n}\n"
},
{
"answer_id": 211468,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 4,
"selected": false,
"text": "/** \n * Get foo\n * @return The value of the foo property\n */\nint getFoo() {\n return foo;\n}\n /** \n * Get the current value of the foo property.\n * The foo property controls the initial guess used by the bla algorithm in\n * {@link #bla}\n * @return The initial guess used by {@link #bla}\n */\nint getFoo() {\n return foo;\n}\n"
},
{
"answer_id": 214163,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 4,
"selected": false,
"text": "/**\n * This method currently launches the blaardh into the bleeyrg.\n */\nvoid execute() { ... }\n void launchBlaardhIntoBleeyrg() { ... }\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24717/"
] |
211,043
|
<p>The IntelliJ IDEA short-cut to reformat source code is <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>L</kbd>. This happens to lock the screen in KDE (Gnome too?). How can I disable this so IntelliJ receives the key sequence?</p>
|
[
{
"answer_id": 32469733,
"author": "Rodrigo Rodrigues",
"author_id": 3128246,
"author_profile": "https://Stackoverflow.com/users/3128246",
"pm_score": 1,
"selected": false,
"text": "Global Keyboard shortcuts KDE Session Manager Lock Session"
},
{
"answer_id": 33958675,
"author": "Andrei C",
"author_id": 2565680,
"author_profile": "https://Stackoverflow.com/users/2565680",
"pm_score": 2,
"selected": false,
"text": "Settings -> Keyboard -> Shortcuts tab -> System -> select Lock screen and press backspace"
},
{
"answer_id": 44681636,
"author": "Shaurya Uppal",
"author_id": 6897603,
"author_profile": "https://Stackoverflow.com/users/6897603",
"pm_score": 1,
"selected": false,
"text": "System settings -> Keyboard -> Shortcut -> System -> LockScreen -> click-it and make changes"
},
{
"answer_id": 62053505,
"author": "Roman Motovilov",
"author_id": 11658289,
"author_profile": "https://Stackoverflow.com/users/11658289",
"pm_score": 0,
"selected": false,
"text": "~/.config/kdeglobals\n~/.config/kglobalshortcutsrc\n~/.config/khotkeysrc\n~/.config/kwinrc\n~/.config/plasma-org.kde.plasma.desktop-appletsrc\n~/.local/share/kxmlgui5/katepart/katepart5ui.rc\n~/.local/share/kxmlgui5/konsole/konsoleui.rc\n~/.local/share/kxmlgui5/konsole/sessionui.rc\n~/.local/share/kxmlgui5/kwrite/kwriteui.rc\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
211,046
|
<p>What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...</p>
<p>Something like this:</p>
<pre><code> if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
hicon = win32gui.LoadImage(hinst,
self.icon,
win32con.IMAGE_ICON,
0,
0,
icon_flags)
</code></pre>
<p>...where self.icon is the filename of the icon I created.</p>
<p>Is there any way to do this in memory? EDIT: All I want to do is create an icon with a 2-digit number displayed on it (weather-taskbar style.</p>
|
[
{
"answer_id": 211304,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 3,
"selected": true,
"text": "from wx import EmptyIcon\nicon = EmptyIcon()\nicon.CopyFromBitmap(your_wxBitmap)\n frame.SetIcon(icon)\n"
},
{
"answer_id": 49098381,
"author": "tenuki",
"author_id": 1033012,
"author_profile": "https://Stackoverflow.com/users/1033012",
"pm_score": 0,
"selected": false,
"text": "from ctypes import *\nfrom ctypes.wintypes import *\n\nCreateIconFromResourceEx = windll.user32.CreateIconFromResourceEx\nsize_x, size_y = 32, 32\nLR_DEFAULTCOLOR = 0\n\nwith open(\"my32x32.png\", \"rb\") as f:\n png = f.read()\nhicon = CreateIconFromResourceEx(png, len(png), 1, 0x30000, size_x, size_y, LR_DEFAULTCOLOR)\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.