qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
283,141
|
<p>I just came across <a href="https://stackoverflow.com/questions/139686/should-local-variable-initialisation-be-mandatory#283127">this question</a> about initializing local variables. Many of the answers debated simplicity/readability <em>vs.</em> robustness. As a developer of (remotely deployed) embedded systems, I always favor robustness and tend to follow several seemingly conflicting rules:</p>
<ul>
<li><p>Handle every error to the best of your ability in a way that allows the device to continue running.</p></li>
<li><p>Design the code to fail <em>as soon as possible</em> after a programming or fatal error occurs.</p></li>
</ul>
<p>We've all been trained to validate input to prevent the device from breaking as a result of user (or other external) input; always assume data may be invalid and test it accordingly.</p>
<p><strong>What other <em>specific</em> practices do you follow to ensure robustness?</strong> Examples are helpful, but I'm also interested in <em>techniques</em> that are universally applicable.</p>
|
[
{
"answer_id": 283159,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "\"hmm why is this 0 at the beginning...\""
},
{
"answer_id": 283163,
"author": "Nate",
"author_id": 36693,
"author_profile": "https://Stackoverflow.com/users/36693",
"pm_score": 3,
"selected": true,
"text": "IRestartable IReusable"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29157/"
] |
283,143
|
<p>I was trying to figure out how to implement method_missing in C# 4, based on all of 2 blog posts floating around on IDynamicObject. </p>
<p>What I want to do is have a Business Logic Layer that has a Repository, and if the method is missing from the Business Logic Layer, just call the Repository and pass through its result. So i have a class that looks like this:</p>
<pre><code>public class CustomerServices : IDynamicObject
{
protected CustomerRepository _Repository = new CustomerRepository();
MetaObject IDynamicObject.GetMetaObject(Expression parameter)
{
return new RepositoryMetaObject<CustomerRepository>(_Repository, parameter);
}
}
</code></pre>
<p>In RepositoryMetaObect I implement the Call method like so:</p>
<pre><code> public override MetaObject Call(CallAction action, MetaObject[] args)
{
typeof(T).GetMethod(action.Name).Invoke(_Repository, getParameterArray(args));
return this;
}
</code></pre>
<p>(The rest of RepositoryMetaObject code probably isn't interesting, but I've included it here: <a href="http://pastie.org/312842" rel="noreferrer">http://pastie.org/312842</a>)</p>
<p>The problem I think is that I'm never doing anything with the result of the Invoke, I'm just returning the MetaObject itself. </p>
<p>Now when I do this:</p>
<pre><code> dynamic service = new CustomerServices();
var myCustomer = service.GetByID(1);
</code></pre>
<p>GetByID is called, but if I try to access a property on myCustomer, is just hangs. </p>
<p>Can anyone please help?</p>
<p>Complete code can be downloaded ehre: <a href="https://dl.getdropbox.com/u/277640/BusinessLogicLayer.zip" rel="noreferrer">https://dl.getdropbox.com/u/277640/BusinessLogicLayer.zip</a></p>
|
[
{
"answer_id": 353847,
"author": "Mik Kardash",
"author_id": 17980,
"author_profile": "https://Stackoverflow.com/users/17980",
"pm_score": 0,
"selected": false,
"text": "return this;\n return RepositoryMetaObject<CustomerRepository>(\n _Repository\n , System.Linq.Expressions.Expression.Constant(returnValue, returnValueType)\n);\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24616/"
] |
283,145
|
<p>I have a solution in Visual Studio 2008 which has multiple projects. One of the projects is a WCF project. Sometimes I just want to debug other projects, but when I press F5, Visual Studio has wcfsvchost.exe launched to host the WCF project even it is not "StartUp Project". </p>
<p>Currently, every time I debugging other projects, I Have to Unload the WCF project to prevent the annoying WcfSvcHost.exe host pop up. However, it is not convenient. Anybody know better idea to prevent WCF project to be hosted in debugging mode?</p>
|
[
{
"answer_id": 283171,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 2,
"selected": false,
"text": "<!--<PublishUrl>http://localhost/WindowsFormsApplication1/</PublishUrl>\n<Install>true</Install>\n<InstallFrom>Web</InstallFrom>\n<UpdateEnabled>true</UpdateEnabled>\n<UpdateMode>Foreground</UpdateMode>\n<UpdateInterval>7</UpdateInterval>\n<UpdateIntervalUnits>Days</UpdateIntervalUnits>\n<UpdatePeriodically>false</UpdatePeriodically>\n<UpdateRequired>false</UpdateRequired>\n<MapFileExtensions>true</MapFileExtensions>\n<ApplicationRevision>0</ApplicationRevision>\n<ApplicationVersion>1.0.0.%2a</ApplicationVersion>\n<IsWebBootstrapper>true</IsWebBootstrapper>\n<UseApplicationTrust>false</UseApplicationTrust>\n<BootstrapperEnabled>true</BootstrapperEnabled>-->\n"
},
{
"answer_id": 1435062,
"author": "Damian",
"author_id": 3390,
"author_profile": "https://Stackoverflow.com/users/3390",
"pm_score": 4,
"selected": false,
"text": "<ProjectTypeGuids>{3D9AD99F-2412-4246-B90B-4EAA41C64699};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\n <ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
283,156
|
<p>So my program needs to go through a plain text file line by line essentially:</p>
<pre><code>Read line 1:
Do commands
loop
Read line2:
Do Commands
loop
</code></pre>
<p>etc until its done with the entire file does anyone know any good coding examples for this, all the tutorials seem to show open and writing/reading textfiles but nothing on how to do it line by line.</p>
|
[
{
"answer_id": 283162,
"author": "Sani Singh Huttunen",
"author_id": 26742,
"author_profile": "https://Stackoverflow.com/users/26742",
"pm_score": 0,
"selected": false,
"text": "Using f As System.IO.FileStream = System.IO.File.OpenRead(\"somefile.txt\")\n Using s As System.IO.StreamReader = New System.IO.StreamReader(f)\n While Not s.EndOfStream\n Dim line As String = s.ReadLine\n\n 'put you line processing code here\n\n End While\n End Using\nEnd Using\n"
},
{
"answer_id": 283173,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 3,
"selected": false,
"text": "For Each line As String In System.IO.File.ReadAllLines(\"file.txt\")\n ' Do Something'\nNext\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,165
|
<p>Are there any known hash algorithms which input a vector of int's and output a single int that work similarly to an inner product?</p>
<p>In other words, I am thinking about a hash algorithm that might look like this in C++:</p>
<pre><code>// For simplicity, I'm not worrying about overflow, and assuming |v| < 7.
int HashVector(const vector<int>& v) {
const int N = kSomethingBig;
const int w[] = {234, 739, 934, 23, 828, 194}; // Carefully chosen constants.
int result = 0;
for (int i = 0; i < v.size(); ++i) result = (result + w[i] * v[i]) % N;
return result;
}
</code></pre>
<p>I'm interested in this because I'm writing up a paper on an algorithm that would benefit from any previous work on similar hashes. In particular, it would be great if there is anything known about the collision properties of a hash algorithm like this.</p>
<p>The algorithm I'm interested in would hash integer vectors, but something for float vectors would also be cool.</p>
<p><strong>Clarification</strong></p>
<p>The hash is intended for use in a hash table for fast key/value lookups. There is no security concern here.</p>
<p>The desired answer is something like a set of constants that provably work particularly well for a hash like this - analogous to a multiplier and modulo which works better than others as a pseudorandom number generator.</p>
<p>For example, some choices of constants for a linear congruential pseudorandom generator are known to give optimal cycle lengths and have easy-to-compute modulos. Maybe someone has done research to show that a certain set of multiplicative constants, along with a modulo constant, in a vector hash can reduce the chance of collisions amongst nearby integer vectors.</p>
|
[
{
"answer_id": 283291,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 1,
"selected": false,
"text": "class tuple:\n def __hash__(self):\n value = 0x345678\n for item in self:\n value = c_mul(1000003, value) ^ hash(item)\n value = value ^ len(self)\n if value == -1:\n value = -2\n return value\n item class int:\n def __hash__(self):\n value = self\n if value == -1:\n value == -2\n return value\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3561/"
] |
283,166
|
<p>How do I do the above? There is mktime function but that treats the input as expressed in local time but how do i perform the conversion if my input tm variable happens to be in UTC.</p>
|
[
{
"answer_id": 9088549,
"author": "Tom",
"author_id": 223201,
"author_profile": "https://Stackoverflow.com/users/223201",
"pm_score": 3,
"selected": false,
"text": "timegm() \n/*\n returns the utc timezone offset\n (e.g. -8 hours for PST)\n*/\nint get_utc_offset() {\n\n time_t zero = 24*60*60L;\n struct tm * timeptr;\n int gmtime_hours;\n\n /* get the local time for Jan 2, 1900 00:00 UTC */\n timeptr = localtime( &zero );\n gmtime_hours = timeptr->tm_hour;\n\n /* if the local time is the \"day before\" the UTC, subtract 24 hours\n from the hours to get the UTC offset */\n if( timeptr->tm_mday < 2 )\n gmtime_hours -= 24;\n\n return gmtime_hours;\n\n}\n\n/*\n the utc analogue of mktime,\n (much like timegm on some systems)\n*/\ntime_t tm_to_time_t_utc( struct tm * timeptr ) {\n\n /* gets the epoch time relative to the local time zone,\n and then adds the appropriate number of seconds to make it UTC */\n return mktime( timeptr ) + get_utc_offset() * 3600;\n\n}\n"
},
{
"answer_id": 15301457,
"author": "liberforce",
"author_id": 518853,
"author_profile": "https://Stackoverflow.com/users/518853",
"pm_score": 3,
"selected": false,
"text": "timegm timegm timegm #include <time.h>\n#include <stdlib.h>\n\ntime_t\nmy_timegm(struct tm *tm)\n{\n time_t ret;\n char *tz;\n\n tz = getenv(\"TZ\");\n if (tz)\n tz = strdup(tz);\n setenv(\"TZ\", \"\", 1);\n tzset();\n ret = mktime(tm);\n if (tz) {\n setenv(\"TZ\", tz, 1);\n free(tz);\n } else\n unsetenv(\"TZ\");\n tzset();\n return ret;\n}\n"
},
{
"answer_id": 21440229,
"author": "Leo Accend",
"author_id": 853331,
"author_profile": "https://Stackoverflow.com/users/853331",
"pm_score": 3,
"selected": false,
"text": "timegm(1) time_t timegm( struct tm *tm ) {\n time_t t = mktime( tm );\n return t + localtime( &t )->tm_gmtoff;\n}\n"
},
{
"answer_id": 24440096,
"author": "Dana",
"author_id": 347298,
"author_profile": "https://Stackoverflow.com/users/347298",
"pm_score": 0,
"selected": false,
"text": "#include <time.h>\n#include <stdio.h>\n#include <stdlib.h> \n\n/*\n * A bit of a hack that lets you pull DST from your Linux box\n */\n\ntime_t timegm( struct tm *tm ) { // From Leo's post, above\n time_t t = mktime( tm );\n return t + localtime( &t )->tm_gmtoff;\n}\nmain()\n{\n struct timespec tspec = {0};\n struct tm tm_struct = {0};\n\n if (gettimeofday(&tspec, NULL) == 0) // clock_gettime() is better but not always avail\n {\n tzset(); // Not guaranteed to be called during gmtime_r; acquire timezone info\n if (gmtime_r(&(tspec.tv_sec), &tm_struct) == &tm_struct)\n {\n printf(\"time represented by original utc time_t: %s\\n\", asctime(&tm_struct));\n // Go backwards from the tm_struct to a time, to pull DST offset. \n time_t newtime = timegm (&tm_struct);\n if (newtime != tspec.tv_sec) // DST offset detected\n {\n printf(\"time represented by new time_t: %s\\n\", asctime(&tm_struct));\n\n double diff = difftime(newtime, tspec.tv_sec); \n printf(\"DST offset is %g (%f hours)\\n\", diff, diff / 3600);\n time_t intdiff = (time_t) diff;\n printf(\"This amounts to %s\\n\", asctime(gmtime(&intdiff)));\n }\n }\n }\n exit(0);\n}\n"
},
{
"answer_id": 29388361,
"author": "apapa",
"author_id": 3986139,
"author_profile": "https://Stackoverflow.com/users/3986139",
"pm_score": 4,
"selected": false,
"text": "_mkgmtime\n"
},
{
"answer_id": 33572892,
"author": "DTiedy",
"author_id": 5534615,
"author_profile": "https://Stackoverflow.com/users/5534615",
"pm_score": 3,
"selected": false,
"text": "time_t _mkgmtime(const struct tm *tm) \n{\n // Month-to-day offset for non-leap-years.\n static const int month_day[12] =\n {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};\n\n // Most of the calculation is easy; leap years are the main difficulty.\n int month = tm->tm_mon % 12;\n int year = tm->tm_year + tm->tm_mon / 12;\n if (month < 0) { // Negative values % 12 are still negative.\n month += 12;\n --year;\n }\n\n // This is the number of Februaries since 1900.\n const int year_for_leap = (month > 1) ? year + 1 : year;\n\n time_t rt = tm->tm_sec // Seconds\n + 60 * (tm->tm_min // Minute = 60 seconds\n + 60 * (tm->tm_hour // Hour = 60 minutes\n + 24 * (month_day[month] + tm->tm_mday - 1 // Day = 24 hours\n + 365 * (year - 70) // Year = 365 days\n + (year_for_leap - 69) / 4 // Every 4 years is leap...\n - (year_for_leap - 1) / 100 // Except centuries...\n + (year_for_leap + 299) / 400))); // Except 400s.\n return rt < 0 ? -1 : rt;\n}\n"
},
{
"answer_id": 42679202,
"author": "Arran Cudbard-Bell",
"author_id": 2117998,
"author_profile": "https://Stackoverflow.com/users/2117998",
"pm_score": 2,
"selected": false,
"text": "extern long timezone tzset() timezone mktime #include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\ntime_t utc_mktime(struct tm *t)\n{\n\n return (mktime(t) - timezone) - ((t->tm_isdst > 0) * 3600);\n} \n\nint main(int argc, char **argv)\n{\n struct tm t = { 0 };\n\n tzset();\n utc_mktime(&t);\n}\n tzset() mktime() tzset() mktime() setenv() TZ"
},
{
"answer_id": 48023344,
"author": "Bo Tian",
"author_id": 2761195,
"author_profile": "https://Stackoverflow.com/users/2761195",
"pm_score": 1,
"selected": false,
"text": "time_t myTimegm(std::tm * utcTime)\n{\n static std::tm tmv0 = {0, 0, 0, 1, 0, 80, 0, 0, 0}; //1 Jan 1980\n static time_t utcDiff = std::mktime(&tmv0) - 315532801;\n\n return std::mktime(utcTime) - utcDiff;\n}\n"
},
{
"answer_id": 68761107,
"author": "Christoph Lipka",
"author_id": 8178357,
"author_profile": "https://Stackoverflow.com/users/8178357",
"pm_score": 1,
"selected": false,
"text": "time_t tm time_t tm time_t tm tm time_t time_t time_t time_t gmtime tm tt;\n// populate tt here\ntt.tm_isdst = 0;\ntime_t tLoc = mktime(&tt);\ntt = *gmtime(&tLoc);\ntt.tm_isdst = 0;\ntime_t tRev = mktime(&tt);\ntime_t tDiff = tLoc - tRev;\ntime_t tUTC = tLoc + tDiff;\n time_t"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24560/"
] |
283,169
|
<p>Suppose I have some code:</p>
<pre><code>let listB = [ 1; 2; 3 ]
</code></pre>
<p>Using Lisp notation, how do I do a <code>car</code> and <code>cadr</code> against this list? I know cons is <code>::</code>.</p>
<p>Or in Scheme, <code>first</code> and <code>rest</code>?</p>
|
[
{
"answer_id": 283184,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": true,
"text": "> let sample = [1;2;3;4];;\n\nval sample : int list\n\n> List.head sample;;\n\nval it : int = 1\n\n> List.tail sample;;\n\nval it : int list = [2; 3; 4]\n"
},
{
"answer_id": 283389,
"author": "simonuk",
"author_id": 28136,
"author_profile": "https://Stackoverflow.com/users/28136",
"pm_score": 3,
"selected": false,
"text": "let list = [1;2;3]\n\nlet rec f = function\n | [] -> 1\n | (x::xs) -> x * (f xs)\n\nf list;\n"
},
{
"answer_id": 284359,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "hd tl hd tl let hd = function [] -> failwith \"hd\" | a::l -> a\nlet tl = function [] -> failwith \"tl\" | a::l -> l\n options > let car = function | hd::tl -> Some hd | _ -> None\n> let cdr = function | hd::[] -> None | hd :: tl -> Some tl | _ -> None\n _"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26227/"
] |
283,180
|
<p>I've got a lot of pages in my site, I'm trying to think of a nice way to separate these into areas that are a little more isolated than just simple directories under my base web project. Is there a way to put my web forms into a separate class library? If so, how is it done?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 283192,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": true,
"text": "Page"
},
{
"answer_id": 47885349,
"author": "Nayas Subramanian",
"author_id": 4315441,
"author_profile": "https://Stackoverflow.com/users/4315441",
"pm_score": 0,
"selected": false,
"text": "if exist \"$(TargetDir)WebForm1.aspx\" move /Y \"$(TargetDir)WebForm1.aspx\" \n\"$(ProjectDir)WebForm1.aspx\"\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11908/"
] |
283,185
|
<p>Is it possible to retrieve the CPUID and MAC address of a client machine from a Ruby on Rails application?. Are there any plugins available for this?</p>
|
[
{
"answer_id": 13275392,
"author": "fqxp",
"author_id": 253954,
"author_profile": "https://Stackoverflow.com/users/253954",
"pm_score": 2,
"selected": false,
"text": "arp $ arp 192.168.1.1\nAddress HWtype HWaddress Flags Mask Iface\n192.168.1.1 ether 1c:c6:3c:48:bc:c0 C wlan0\n HWaddress"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,193
|
<p>I have a list of email address which I want to distribute evenly by domain.</p>
<p>For example:</p>
<p>let the list be, </p>
<pre><code>a@a.com
b@a.com
c@a.com
a@b.com
b@b.com
c@c.com
</code></pre>
<p>The output should be </p>
<pre><code>a@a.com
a@b.com
c@c.com
b@a.com
b@b.com
c@a.com
</code></pre>
<p>The source list is not sorted by domain as in example, but can be sorted by domain, if that can help. What would be an efficient (single/two pass?) algorithm of doing this?</p>
<p>raj</p>
|
[
{
"answer_id": 283200,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 0,
"selected": false,
"text": "$sortedList = array();\n$tempList\n$emailList = array('a@a.com', 'b@a.com', 'c@b.com', 'd@b.com', 'e@c.com', 'f@a.com');\n\n$emailCount = 0;\nforeach ( $emailList as $email ) {\n list($username, $domain) = explode('@', $email);\n $tempList[$domain][] = $user;\n $emailCount++;\n}\n\nfor ( $i = 0; $i < $emailCount; $i++ ) {\n $listIndex = $i % count($tempList);\n if ( !empty($tempList[$listIndex]) ) {\n $sortedList[] = $tempList[$listIndex][0];\n unset($tempList[$listIndex][0]);\n } else {\n unset$tempList[$listIndex]);\n }\n}\n"
},
{
"answer_id": 284198,
"author": "Rajkumar S",
"author_id": 25453,
"author_profile": "https://Stackoverflow.com/users/25453",
"pm_score": 1,
"selected": true,
"text": "[[\"A\", 13], [\"B\", 5], [\"C\", 3], [\"D\", 1]] \n AABABAACABAACABAACABAD\n require \"pp\"\n\ndef shuffle (total, num)\n ret_arr = Array.new\n intervel = total/num.to_f\n 0.upto(num-1) do |i|\n val = i * intervel\n ret_arr << val.floor\n end\n return ret_arr\nend\n\nfreq_table = [[\"A\", 13], [\"B\", 5], [\"C\", 3], [\"D\", 1]]\n\npp freq_table\ntotal = 0\nfreq_table.collect {|i| total += i[1] }\nfinal_array = Array.new(total,0)\nprint final_array.to_s + \"\\n\\n\"\nplaced = 0\n\nfreq_table.each do |i|\n placements = shuffle(total - placed, i[1])\n placements.each do |j|\n free_index = -1\n 0.upto final_array.size do |k|\n free_index += 1 if (final_array[k] == 0 || final_array[k] == i[0])\n if j == free_index\n final_array[k] = i[0]\n break\n end\n end\n end\n print \"Placing #{i[1]} #{i[0]}s over #{total - placed} positions\\n\"\n pp placements\n print final_array.to_s + \"\\n\\n\"\n placed += i[1]\nend\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25453/"
] |
283,202
|
<p>we are writing tests for a COM library written in VB 6.0.The problem we are facing is that, we are unable to access events declared in VB( withevents). We get exception, "object does not support set of events". How can we overcome this problem?</p>
|
[
{
"answer_id": 295316,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Option Explicit\n\nPublic Event SavedSuccessfully()\n\nPublic Sub Execute(ByVal vAge As Integer, ByVal vName As String, ByVal vAddress As String)\n\n RaiseEvent SavedSuccessfully\n\nEnd Sub\n Private WithEvents dbCommand As DatabaseCommand\n\nPublic Sub Init(ByVal vDBCommand As DatabaseCommand)\n\n Set dbCommand = vDBCommand\n\nEnd Sub\n\nPrivate Sub dbCommand_SavedSuccessfully()\n 'not implemented\nEnd Sub\n MockRepository repository = new MockRepository();\n\nPersonLib.DatabaseCommand db = repository.DynamicMock<PersonLib.DatabaseCommand>();\n\nPersonLib.PersonClass person = new PersonLib.PersonClass();\n\nperson.Init(db); --- this line throws error - Object or class does not support the set of events\n"
},
{
"answer_id": 299579,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 2,
"selected": false,
"text": "repository.DynamicMock<PersonLib.DatabaseCommand>();\n DatabaseCommand PersonClass.Init PersonClass.Init Set dbCommand = vDBCommand Set DatabaseCommand dbCommand WithEvents dbCommand DatabaseCommand DatabaseCommand DatabaseCommand"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,205
|
<p>I am an intermediate C programmer. If you have made any coding mistake that you came to know later that it was the most hazardous / harmful to the total application please share that code or description. I want to know this because in future I may come across such situations and I want to have your advice to avoid such mistakes.</p>
|
[
{
"answer_id": 283212,
"author": "Daniel Kreiseder",
"author_id": 31406,
"author_profile": "https://Stackoverflow.com/users/31406",
"pm_score": 5,
"selected": false,
"text": "if (c = 1) // insert code here\n"
},
{
"answer_id": 283215,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "for(int i = 0; i<10; ++i)\n //code here\n //code added later\n"
},
{
"answer_id": 283248,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 5,
"selected": true,
"text": "strcpy() man strcpy strcpy() strcat() strncpy() strcpy() #define STRNCPY(A,B,C) do {strncpy(A,B,C); A[C] = 0; } while (0)"
},
{
"answer_id": 283264,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 4,
"selected": false,
"text": "\\0"
},
{
"answer_id": 283296,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 4,
"selected": false,
"text": "if(a == true);\n{\n //Do sth when it is true. But it is allways executed.\n}\n for(i=0; i<max_iterations;i++);\n{\n //Do sth but unexpectedly only once\n}\n"
},
{
"answer_id": 283388,
"author": "Marco M.",
"author_id": 28375,
"author_profile": "https://Stackoverflow.com/users/28375",
"pm_score": 2,
"selected": false,
"text": "char* c = malloc(...);\n.\n.\n.\nfree(c); \n.\n.\n.\nc[...] = ...; \n // char* s is an input string\nchar* c = malloc(strlen(s));\nstrcpy(c, s);\n char* c = ...;\nint i = *((int*)c); // <-- alignment fault\n"
},
{
"answer_id": 283401,
"author": "ani625",
"author_id": 18755,
"author_profile": "https://Stackoverflow.com/users/18755",
"pm_score": 2,
"selected": false,
"text": "while(a)\n{ \n // code - where 'a' never reaches 0 :( \n}\n"
},
{
"answer_id": 284291,
"author": "UberJumper",
"author_id": 34395,
"author_profile": "https://Stackoverflow.com/users/34395",
"pm_score": 0,
"selected": false,
"text": "#include <string>\n"
},
{
"answer_id": 288494,
"author": "eaanon01",
"author_id": 36986,
"author_profile": "https://Stackoverflow.com/users/36986",
"pm_score": 2,
"selected": false,
"text": "if(55000 < my_var < 65000)\n if( (55000<my_var) < 65000)\n if( (55000<my_var) || (my_var<65000))\n get_data(BYTE **dataptr)\n{ \n ubyte* data = malloc(10);\n ... code ...\n *dataptr = &data[1];\n}\n\n main()\n {\n BYTE *data\n get_data(&data);\n free(data);\n }\n get_data()"
},
{
"answer_id": 289411,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "if (importantvar = importantfunction() == VALID_CODE)\n if ((important var = importantfunction()) == VALID_CODE)\n"
},
{
"answer_id": 321393,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 1,
"selected": false,
"text": "(cond\n ((eq a foo)(bar ...\n ....\n ))\n )\n if (a == foo){\n bar(...);\n ....\n }\n"
},
{
"answer_id": 4151793,
"author": "Crashworks",
"author_id": 53543,
"author_profile": "https://Stackoverflow.com/users/53543",
"pm_score": 2,
"selected": false,
"text": "double d; // d gets populated with a large number from somewhere\nshort s = d ; // overflow\n"
},
{
"answer_id": 35354489,
"author": "Ji Ho Jeon",
"author_id": 5544700,
"author_profile": "https://Stackoverflow.com/users/5544700",
"pm_score": 0,
"selected": false,
"text": "; } ,"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
283,209
|
<p>do I have to register the HttpVerb constraint in my route definition (when i'm registering routes) if i have decorated my action method with the [AcceptVerbs(..)] attribute already?</p>
<p>eg. i have this.</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection formCollection)
{ .. }
</code></pre>
<p>do i need to add this to the route that refers to this action, as a constraint?</p>
|
[
{
"answer_id": 285850,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 6,
"selected": true,
"text": "Create HomeController AcceptVerbs public ActionResult Create(int id) { .. }\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Create(FormCollection formCollection) { .. }\n /home/create AcceptVerbs HttpMethodConstraint /home/create"
},
{
"answer_id": 2549310,
"author": "MrByte",
"author_id": 19710,
"author_profile": "https://Stackoverflow.com/users/19710",
"pm_score": 1,
"selected": false,
"text": "[ActionName(\"ItemEdit\"), AcceptVerbs(HttpVerbs.Post)]\npublic virtual object ItemSave(Menu sampleInput)\n AddRoute(\n \"SampleEdit\",\n \"Admin/{sampleID}/Edit\",\n new { controller = \"Sample\", action = \"ItemEdit\", validateAntiForgeryToken = true },\n new { areaID = new IsGuid() },\n new { Namespaces = controllerNamespaces }\n );\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
283,214
|
<p>Is there an application , which can parse a given set of stored procedures (SQL Server 2000) and gets all tables and associated columns that are being used in it.
The stored procedure can have tables from different databases.</p>
<p>Output should be like
TableA
columnA
columnC
columnD</p>
<p>TableB
columnE
columnF
columnG</p>
<p>I have written an small application using Database Edition GDR Any one interested can refer to <a href="http://tsqlparsergdr.codeplex.com" rel="nofollow noreferrer">http://tsqlparsergdr.codeplex.com</a> </p>
|
[
{
"answer_id": 283272,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": -1,
"selected": false,
"text": "[...]\n@MyDate datetime\n\nAS\n\n IF (day(@MyDate) = 1)\n BEGIN\n SELECT * FROM MyFirstTable\n RETURN\n END\n\n IF (@MyDate > getdate())\n SELECT MyID, MyText FROM MySecondTable WHERE ADate > @MyDate\n ELSE\n EXEC Other_StoredProcedure @MyType, @MyDate\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21195/"
] |
283,222
|
<p>What's the best way to take some plain text (not PHP code) which contains PHP-style variables, and then substitute in the value of the variable. This is kinda hard to describe, so here's an example.</p>
<pre><code>// -- myFile.txt --
Mary had a little $pet.
// -- parser.php --
$pet = "lamb";
// open myFile.txt and transform it such that...
$newContents = "Mary had a little lamb.";
</code></pre>
<p>I've been considering using a regex or perhaps <code>eval()</code>, though I'm not sure which would be easiest. This script is only going to be running locally, so any worries regarding security issues and <code>eval()</code> do not apply <em>(i think?)</em>.</p>
<p>I'll also just add that I can get all the necessary variables into an array by using <code>get_defined_vars()</code>:</p>
<pre><code>$allVars = get_defined_vars();
echo $pet; // "lamb"
echo $allVars['pet']; // "lamb"
</code></pre>
|
[
{
"answer_id": 283231,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "$allVars = get_defined_vars();\n$file = file_get_contents('myFile.txt');\n\nforeach ($allVars as $var => $val) {\n $file = preg_replace(\"@\\\\$\" . $var . \"([^a-zA-Z_0-9\\x7f-\\xff]|$)@\", $val . \"\\\\1\", $file);\n}\n"
},
{
"answer_id": 283232,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": false,
"text": "eval() \\$\\w+\n preg_replace_callback() $allVars = get_defined_vars();\n$file = file_get_contents('myFile.txt');\n\n// unsure if you have to use single or double backslashes here for PHP to understand\npreg_replace_callback ('/\\$(\\w+)/', \"find_replacements\", $file);\n\n// replace callback function\nfunction find_replacements($match)\n{\n global $allVars;\n if (array_key_exists($match[1], $allVars))\n return $allVars[$match[1]];\n else\n return $match[0];\n}\n"
},
{
"answer_id": 283237,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 0,
"selected": false,
"text": "// -- myFile.txt --\nMary had a little %pet%.\n\n// -- parser.php --\n$pet = \"lamb\";\n$fileName = myFile.txt\n\n$currentContents = file_get_contents($fileName);\n\n$newContents = str_replace('%pet%', $pet, $currentContents);\n\n// $newContents == 'Mary had a little lamb.'\n"
},
{
"answer_id": 283339,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "$text = 'this is a $test'; // single quotes to simulate getting it from a file\n$test = 'banana';\n$text = eval('return \"' . addslashes($text) . '\";');\necho $text; // this is a banana\n"
},
{
"answer_id": 285501,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 2,
"selected": false,
"text": "<?= $pet ?> //myFile.txt\nMary had a little <?= $pet ?>.\n\n//parser.php\n\n$pet = \"lamb\";\nob_start();\ninclude(\"myFile.txt\");\n$contents = ob_end_clean();\n\necho $contents;\n Mary had a little lamb.\n"
},
{
"answer_id": 285514,
"author": "user37125",
"author_id": 37125,
"author_profile": "https://Stackoverflow.com/users/37125",
"pm_score": -1,
"selected": false,
"text": "$text = file_get_contents('/path/to/myFile.txt'); // \"Mary had a little $pet.\"\n$allVars = get_defined_vars(); // array('pet' => 'lamb');\n$translate = array();\n\nforeach ($allVars as $key => $value) {\n $translate['$' . $key] = $value; // prepend '$' to vars to match text\n}\n\n// translate is now array('$pet' => 'lamb');\n\n$text = strtr($text, $translate);\n\necho $text; // \"Mary had a little lamb.\"\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
283,239
|
<p>In my models, there are lots of attributes and methods that perform some calculation based on the model instance's attributes. I've been having the methods return nil if the attributes that the calculations depend on are nil. As a consequence of this design decision, I'm doing a lot of nil checks before displaying these values in my views. </p>
<p>I thought about having these methods return zero instead of nil when they don't have enough information, but I chose nil because zero is a valid computation result and nil implies that there was not enough information.</p>
<p>Should I return 0 instead of nil? Is there any other pattern that I could use to avoid doing a bunch of nil checks in my views? </p>
|
[
{
"answer_id": 283319,
"author": "Patrick McKenzie",
"author_id": 15046,
"author_profile": "https://Stackoverflow.com/users/15046",
"pm_score": 3,
"selected": false,
"text": "Food calculate_deliciousness_of_pie_or_nil_for_burger"
},
{
"answer_id": 285056,
"author": "nickh",
"author_id": 34478,
"author_profile": "https://Stackoverflow.com/users/34478",
"pm_score": 2,
"selected": false,
"text": "{:result => 1234}\n {:error => 'Insufficient attributes to calculate result.'}\n <% if result = some_method -%>\n Your result is <%=h result -%>.<br />\n<% end -%>\n <% display_some_method %>\n"
},
{
"answer_id": 394208,
"author": "maurycy",
"author_id": 48541,
"author_profile": "https://Stackoverflow.com/users/48541",
"pm_score": 1,
"selected": false,
"text": "Apartment#address_visible?(current_user) #try"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36049/"
] |
283,251
|
<p>I need to read account number from Maestro/Mastercard with smart card reader. I am using Java 1.6 and its javax.smartcardio package. I need to send APDU command which will ask EMV application stored on card's chip for PAN number. Problem is, I cannot find regular byte array to construct APDU command which will return needed data anywhere... </p>
|
[
{
"answer_id": 283452,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 0,
"selected": false,
"text": "byte[] readFile(CardChannel channel) throws CardException {\n CommandAPDU command = new CommandAPDU(0xB0, 0x60, 0x10, 0x00);\n ResponseAPDU response = channel.transmit(command);\n return response.getData();\n}\n"
},
{
"answer_id": 283760,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 0,
"selected": false,
"text": "byte[] readPan(CardChannel channel) throws CardException {\n CommandAPDU command = new CommandAPDU(0x00, 0xB2, 0x5a, 0x14, 250);\n ResponseAPDU response = channel.transmit(command);\n return response.getData();\n}\n"
},
{
"answer_id": 286681,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 4,
"selected": true,
"text": "void selectApplication(CardChannel channel) throws CardException {\n byte[] masterCardRid = new byte[]{0xA0, 0x00, 0x00, 0x00, 0x04};\n CommandAPDU command = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, masterCardRid);\n ResponseAPDU response = channel.transmit(command);\n return response.getData();\n}\n"
},
{
"answer_id": 304591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "CardChannel channel = card.getBasicChannel(); \n\n byte[] selectMaestro={(byte)0x00, (byte)0xA4,(byte)0x04,(byte)0x00 ,(byte)0x07 ,(byte)0xA0 ,(byte)0x00 ,(byte)0x00 ,(byte)0x00 ,(byte)0x04 ,(byte)0x30 ,(byte)0x60 ,(byte)0x00};\n byte[] getProcessingOptions={(byte)0x80,(byte)0xA8,(byte)0x00,(byte)0x00,(byte)0x02,(byte)0x83,(byte)0x00,(byte)0x00};\n byte[] readRecord={(byte)0x00,(byte)0xB2,(byte)0x02,(byte)0x0C,(byte)0x00};\n\n ResponseAPDU r=null;\n\n try {\n ATR atr = card.getATR(); //reset kartice\n\n CommandAPDU capdu=new CommandAPDU( selectMaestro );\n\n r=card.getBasicChannel().transmit( capdu );\n\n capdu=new CommandAPDU(getProcessingOptions);\n r=card.getBasicChannel().transmit( capdu );\n\n\n capdu=new CommandAPDU(readRecord);\n r=card.getBasicChannel().transmit( capdu );\n"
},
{
"answer_id": 556248,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "atr = open();\nprints(atr);\n\nprints(\"[Step 1] Select 1PAY.SYS.DDF01 to get the PSE directory\");\ncmd = new ISOSelect(ISOSelect.SELECT_AID, EMV4_1.AID_1PAY_SYS_DDF01);\ncard_response = execute(cmd);\nprints(card_response);\nSFI = NumUtil.hex2String((byte)((1 < < 3) | 4));\n\n// try SFI 1 record 1\nprints(\"[Step 2] Send READ RECORD with 0 to find out where the record is\");\nread = new EMVReadRecord(SFI, \"01\", \"00\");\ncard_response = execute(read);\nprints(card_response);\nbyte_size = NumUtil.hex2String(card_response.getStatusWord().getSw2());\n\nprints(\"[Step 3] Send READ RECORD with 1C to get the PSE data\");\nread = new EMVReadRecord(SFI, \"01\", byte_size);\ncard_response = execute(read);\nprints(card_response);\n// the AID is A0000000031010\nprints(\"[Step 4] Now that we know the AID, select the application\");\n\ncmd = new ISOSelect(ISOSelect.SELECT_AID, \"A0000000031010\");\ncard_response = execute(cmd);\nprints(card_response);\nprints(\"[Step 5] Send GET PROCESSING OPTIONS command\");\n\ncmd = new EMVGetProcessingOptions();\ncard_response = execute(cmd);\nprints(card_response);\n\n// SFI for the first group of AFL is 0C\n\nprints(\"[Step 6] Send READ RECORD with 0 to find out where the record is\");\nread = new EMVReadRecord(\"0C\", \"01\", \"00\");\ncard_response = execute(read);\nprints(card_response);\nbyte_size = NumUtil.hex2String(card_response.getStatusWord().getSw2());\n\nprints(\"[Step 7] Use READ RECORD with the given number of bytes to retrieve the data\");\nread = new EMVReadRecord(\"0C\", \"01\", byte_size);\ncard_response = execute(read);\nprints(card_response);\n\ndata = new TLV(card_response.getData());\n\nclose();\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,263
|
<p>I'm putting a crontab job for updating with apt-get once a day (running Debian Lenny, there are updates almost daily). But almost all examples i've seen of this cron job invoke the -d flag. </p>
<p>This elicits 4 questions:</p>
<ul>
<li>Why should I only download the
packages and not install them?</li>
<li>Doesn't this defeat the purpose of
running it automatically?</li>
<li>Don't I have to go in and actually
install the updates later?</li>
<li>Is it safe for me to run the cron
job without the -d flag?</li>
</ul>
|
[
{
"answer_id": 286517,
"author": "Darren Greaves",
"author_id": 151,
"author_profile": "https://Stackoverflow.com/users/151",
"pm_score": 1,
"selected": false,
"text": "/usr/bin/apt-get update && /usr/bin/apt-get -s -u upgrade\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50/"
] |
283,275
|
<p>I want to store a large result set from database in memory. Every record has variable length and access time must be as fast as arrays. What is the best way to implement this? I was thinking of keeping offsets in a separate table and storing all of the records consecutively? Is it odd? (Programming Language: Delphi)</p>
|
[
{
"answer_id": 283650,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 0,
"selected": false,
"text": "type\n pMyRecord : ^TMyRecord;\n...\n...\n...\nvar\n p : pMyRecord;\n...\n...\nNew(p);\nwith p^ do\nbegin\n ...\n ...\nend;\n...\nMyList.Add(P);\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36830/"
] |
283,284
|
<p>When I create a TFS report of a query with the Excel integration features (we are using Excel 2003), Excel resets formatting of all cells after clicking the "Refresh" button in the TFS Toolbar.</p>
<p>Our team likes to print this report and drag it into our weekly meeting as it accurately lists all our open tasks. Bad formatting is a pain, though: Vertical alignment set to "bottom" and no borders on cells makes it nearly impossible to know when one Task/Bug starts and the other ends...</p>
|
[
{
"answer_id": 298088,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 3,
"selected": true,
"text": "tfpt.exe tfpt query /format:xml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<xsl:stylesheet version=\"1.0\" \n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" \n xmlns:spss=\"http://xml.spss.com/spss/oms\"\n exclude-result-prefixes=\"spss\">\n\n<xsl:template match=\"/\">\n<html>\n <head>\n <title>All active Work Items</title>\n </head>\n <body>\n <table border=\"1\" frame=\"border\" rules=\"all\">\n <tr><th>ID</th><th>Area Path</th><th>Assigned To</th><th>Title</th><th>Description</th></tr>\n <xsl:for-each select=\".//WorkItem\">\n <tr>\n <td><xsl:value-of select=\"./Field[@RefName='System.Id']/@Value\"/></td>\n <td><xsl:value-of select=\"./Field[@RefName='System.AreaPath']/@Value\"/></td>\n <td><xsl:value-of select=\"./Field[@RefName='System.AssignedTo']/@Value\"/></td>\n <td><xsl:value-of select=\"./Field[@RefName='System.Title']/@Value\"/></td>\n <td><xsl:value-of select=\"./Field[@RefName='System.Description']/@Value\"/></td>\n </tr>\n </xsl:for-each>\n </table> \n </body> \n</html>\n</xsl:template>\n\n</xsl:stylesheet>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
283,294
|
<p>I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application?
I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?</p>
|
[
{
"answer_id": 284607,
"author": "Ben",
"author_id": 3553,
"author_profile": "https://Stackoverflow.com/users/3553",
"pm_score": 4,
"selected": false,
"text": "import pdb; pdb.set_trace() settings.py logging.basicConfig(\n level = logging.DEBUG,\n format = '%(asctime)s %(levelname)s %(message)s',\n filename = '/tmp/mylog.log',\n filemode = 'w'\n)\n /tmp/mylog.log import logging\nlogging.debug(\"Something happened\")\n"
},
{
"answer_id": 286703,
"author": "Chad",
"author_id": 37309,
"author_profile": "https://Stackoverflow.com/users/37309",
"pm_score": 2,
"selected": false,
"text": "AJAX console Error"
},
{
"answer_id": 1665783,
"author": "Matthew Talbert",
"author_id": 27611,
"author_profile": "https://Stackoverflow.com/users/27611",
"pm_score": 5,
"selected": true,
"text": "pdb python manage.py runserver --noreload\n import sys\nsys.path.append('/path/to/directory/containing/views.py')\n"
},
{
"answer_id": 7418949,
"author": "user111443",
"author_id": 111443,
"author_profile": "https://Stackoverflow.com/users/111443",
"pm_score": 1,
"selected": false,
"text": "import pdb; pdb.set_trace()\n shell python ./manage.py runserver\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] |
283,297
|
<p>I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..</p>
<pre><code>const char *GetString()
{
std::stringstream ss;
ss << "The random number is: " << rand();
return ss.str().c_str();
}
</code></pre>
<p>could the c string be destroyed when ss falls off the stack? I'm assuming so...</p>
<p>Another option may be to create a new string on the heap, but what is going to deallocate that?</p>
<pre><code>const char *GetString()
{
std::stringstream ss;
ss << "The random number is: " << rand();
char *out = new char[ss.str().size()];
strcpy(ss.str().c_str(), out);
return out;//is out ever deleted?
}
</code></pre>
<p>The same goes for pointers to other things as well as strings.</p>
|
[
{
"answer_id": 283314,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 0,
"selected": false,
"text": "CreateString()\n GetString()\n"
},
{
"answer_id": 283317,
"author": "n-alexander",
"author_id": 23420,
"author_profile": "https://Stackoverflow.com/users/23420",
"pm_score": 4,
"selected": true,
"text": "const char *GetString()\n{\n return \"a static string in DATA segment - no need to delete\";\n}\n char *GetString()\n{\n std::stringstream ss;\n ss << \"The random number is: \" << rand();\n return strdup( ss.str().c_str() ); // allocated in C style with malloc()\n}\n\nvoid foo()\n{\n char *p = GetString();\n printf(\"string: %s\", p));\n free( p ); // must not forget to free(), must not use delete()\n}\n char *GetString(char *buffer, size_t len)\n{\n std::stringstream ss;\n ss << \"The random number is: \" << rand();\n return strncpy(buffer, ss.str().c_str(), len); // caller allocates memory\n}\n\nvoid foo()\n{\n char buffer[ 100 ];\n printf(\"string: %s\", GetString(buffer, sizeof( buffer ))); // no memory leaks\n}\n"
},
{
"answer_id": 283399,
"author": "sep",
"author_id": 30333,
"author_profile": "https://Stackoverflow.com/users/30333",
"pm_score": 0,
"selected": false,
"text": "const char *GetString()\n{\n static char *out;\n std::stringstream ss;\n ss << \"The random number is: \" << rand();\n delete[] out;\n char *out = new char[ss.str().size()];\n strcpy(ss.str().c_str(), out);\n return out;//is out ever deleted?\n}\n void GetString(char *out, int maxlen);\n"
},
{
"answer_id": 283418,
"author": "Enno",
"author_id": 30404,
"author_profile": "https://Stackoverflow.com/users/30404",
"pm_score": 0,
"selected": false,
"text": "void foo() {\n char result[64];\n GetString(result, sizeof(result));\n puts(result);\n} int GetString(char * dst, size_t len) {\n std::stringstream ss;\n ss << \"The random number is: \" << rand();\n strncpy(ss.str().c_str(), dst, len);\n}"
},
{
"answer_id": 24023830,
"author": "Alex",
"author_id": 175157,
"author_profile": "https://Stackoverflow.com/users/175157",
"pm_score": 0,
"selected": false,
"text": "const char* typedef void (*ResultCallback)( void* context, const char* result );\n\nvoid Foo( ResultCallback resultCallback, void* context )\n{\n std::string s = \"....\";\n resultCallback( context, s.c_str() );\n}\n ResultCallback result void* void UserCallback( void* context, const char* result )\n{\n char** copied = context;\n *copied = malloc( strlen(result)+1 );\n strcpy( *copied, result );\n}\n\nvoid User()\n{\n char* result = NULL;\n\n Foo( UserCallback, &result );\n\n // Use result...\n if( result != NULL )\n printf(\"%s\", result);\n\n free( result );\n}\n"
},
{
"answer_id": 24025260,
"author": "Deduplicator",
"author_id": 3204551,
"author_profile": "https://Stackoverflow.com/users/3204551",
"pm_score": 0,
"selected": false,
"text": "strcpy() strcpy_s() snprintf fread gets qsort_s qsort fopen fclose strdup free std::shared_ptr asctime"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
283,299
|
<p>I have a large array with a range of integers that are mostly continuous, eg 1-100, 110-160, etc. All integers are positive.
What would be the best algorithm to compress this?<br/><br/>
I tried the deflate algorithm but that gives me only 50% compression.
Note that the algorithm cannot be lossy.</p>
<p>All numbers are unique and progressively increasing.</p>
<p>Also if you can point me to the java implementation of such algorithm that would be great.</p>
|
[
{
"answer_id": 1081758,
"author": "brianegge",
"author_id": 14139,
"author_profile": "https://Stackoverflow.com/users/14139",
"pm_score": 4,
"selected": false,
"text": "None 1.0\nDeflate 0.50\nFiltered 0.34\nBZip2 0.11\nLzma 0.06\n"
},
{
"answer_id": 1081776,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "1-100, 110-160\n 0,99,8,50\n 00 63 08 32\n 299 = 100101100 = (in blocks of 7): 0000010 0101100\n 1 0101100 (leading one since continuation)\n0 0000010 (leading zero as no more)\n AC 02\n using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nstatic class Program\n{\n static void Main()\n {\n var data = new List<int>();\n data.AddRange(Enumerable.Range(1, 100));\n data.AddRange(Enumerable.Range(110, 51));\n int[] arr = data.ToArray(), arr2;\n\n using (MemoryStream ms = new MemoryStream())\n {\n Encode(ms, arr);\n ShowRaw(ms.GetBuffer(), (int)ms.Length);\n ms.Position = 0; // rewind to read it...\n arr2 = Decode(ms);\n }\n }\n static void ShowRaw(byte[] buffer, int len)\n {\n for (int i = 0; i < len; i++)\n {\n Console.Write(buffer[i].ToString(\"X2\"));\n }\n Console.WriteLine();\n }\n static int[] Decode(Stream stream)\n {\n var list = new List<int>();\n uint skip, take;\n int last = 0;\n while (TryDecodeUInt32(stream, out skip)\n && TryDecodeUInt32(stream, out take))\n {\n last += (int)skip+1;\n for(uint i = 0 ; i <= take ; i++) {\n list.Add(last++);\n }\n }\n return list.ToArray();\n }\n static int Encode(Stream stream, int[] data)\n {\n if (data.Length == 0) return 0;\n byte[] buffer = new byte[10];\n int last = -1, len = 0;\n for (int i = 0; i < data.Length; )\n {\n int gap = data[i] - 2 - last, size = 0;\n while (++i < data.Length && data[i] == data[i - 1] + 1) size++;\n last = data[i - 1];\n len += EncodeUInt32((uint)gap, buffer, stream)\n + EncodeUInt32((uint)size, buffer, stream);\n }\n return len;\n }\n public static int EncodeUInt32(uint value, byte[] buffer, Stream stream)\n {\n int count = 0, index = 0;\n do\n {\n buffer[index++] = (byte)((value & 0x7F) | 0x80);\n value >>= 7;\n count++;\n } while (value != 0);\n buffer[index - 1] &= 0x7F;\n stream.Write(buffer, 0, count);\n return count;\n }\n public static bool TryDecodeUInt32(Stream source, out uint value)\n {\n int b = source.ReadByte();\n if (b < 0)\n {\n value = 0;\n return false;\n }\n\n if ((b & 0x80) == 0)\n {\n // single-byte\n value = (uint)b;\n return true;\n }\n\n int shift = 7;\n\n value = (uint)(b & 0x7F);\n bool keepGoing;\n int i = 0;\n do\n {\n b = source.ReadByte();\n if (b < 0) throw new EndOfStreamException();\n i++;\n keepGoing = (b & 0x80) != 0;\n value |= ((uint)(b & 0x7F)) << shift;\n shift += 7;\n } while (keepGoing && i < 4);\n if (keepGoing && i == 4)\n {\n throw new OverflowException();\n }\n return true;\n }\n}\n"
},
{
"answer_id": 37038095,
"author": "Deen Foxx",
"author_id": 1899881,
"author_profile": "https://Stackoverflow.com/users/1899881",
"pm_score": 2,
"selected": false,
"text": " // $integers_array can contain any integers; no floating point, please. Duplicates okay.\n $integers_array = [118, 68, -9, 82, 67, -36, 15, 27, 26, 138, 45, 121, 72, 63, 73, -35,\n 68, 46, 37, -28, -12, 42, 101, 21, 35, 100, 44, 13, 125, 142, 36, 88,\n 113, -40, 40, -25, 116, -21, 123, -10, 43, 130, 7, 39, 69, 102, 24,\n 75, 64, 127, 109, 38, 41, -23, 21, -21, 101, 138, 51, 4, 93, -29, -13];\n\n // Order from least to greatest... This routine does NOT save original order of integers.\n sort($integers_array, SORT_NUMERIC); \n\n // Start with the least value... NOTE: This removes the first value from the array.\n $start = $current = array_shift($integers_array); \n\n // This caps the end of the array, so we can easily get the last step or span value.\n array_push($integers_array, $start - 1);\n\n // Create the compressed array...\n $compressed_array = [$start];\n foreach ($integers_array as $next_value) {\n // Range of $current to $next_value is our \"skip\" range. I call it a \"step\" instead.\n $step = $next_value - $current;\n if ($step == 1) {\n // Took a single step, wait to find the end of a series of seqential numbers.\n $current = $next_value;\n } else {\n // Range of $start to $current is our \"take\" range. I call it a \"span\" instead.\n $span = $current - $start;\n // If $span is positive, use \"negative\" to identify these as sequential numbers. \n if ($span > 0) array_push($compressed_array, -$span);\n // If $step is positive, move forward. If $step is zero, the number is duplicate.\n if ($step >= 0) array_push($compressed_array, $step);\n // In any case, we are resetting our start of potentialy sequential numbers.\n $start = $current = $next_value;\n }\n }\n\n // OPTIONAL: The following code attempts to compress things further in a variety of ways.\n\n // A quick check to see what pack size we can use.\n $largest_integer = max(max($compressed_array),-min($compressed_array));\n if ($largest_integer < pow(2,7)) $pack_size = 'c';\n elseif ($largest_integer < pow(2,15)) $pack_size = 's';\n elseif ($largest_integer < pow(2,31)) $pack_size = 'l';\n elseif ($largest_integer < pow(2,63)) $pack_size = 'q';\n else die('Too freaking large, try something else!');\n\n // NOTE: I did not implement the MSB feature mentioned by Marc Gravell.\n // I'm just pre-pending the $pack_size as the first byte, so I know how to unpack it.\n $packed_string = $pack_size;\n\n // Save compressed array to compressed string and binary packed string.\n $compressed_string = '';\n foreach ($compressed_array as $value) {\n $compressed_string .= ($value < 0) ? $value : '+'.$value;\n $packed_string .= pack($pack_size, $value);\n }\n\n // We can possibly compress it more with gzip if there are lots of similar values. \n $gz_string = gzcompress($packed_string);\n\n // These were all just size tests I left in for you.\n $base64_string = base64_encode($packed_string);\n $gz64_string = base64_encode($gz_string);\n $compressed_string = trim($compressed_string,'+'); // Don't need leading '+'.\n echo \"<hr>\\nOriginal Array has \"\n .count($integers_array)\n .' elements: {not showing, since I modified the original array directly}';\n echo \"<br>\\nCompressed Array has \"\n .count($compressed_array).' elements: '\n .implode(', ',$compressed_array);\n echo \"<br>\\nCompressed String has \"\n .strlen($compressed_string).' characters: '\n .$compressed_string;\n echo \"<br>\\nPacked String has \"\n .strlen($packed_string).' (some probably not printable) characters: '\n .$packed_string;\n echo \"<br>\\nBase64 String has \"\n .strlen($base64_string).' (all printable) characters: '\n .$base64_string;\n echo \"<br>\\nGZipped String has \"\n .strlen($gz_string).' (some probably not printable) characters: '\n .$gz_string;\n echo \"<br>\\nBase64 of GZipped String has \"\n .strlen($gz64_string).' (all printable) characters: '\n .$gz64_string;\n\n // NOTICE: The following code reverses the process, starting form the $compressed_array.\n\n // The first value is always the starting value.\n $current_value = array_shift($compressed_array);\n $uncompressed_array = [$current_value];\n foreach ($compressed_array as $val) {\n if ($val < -1) {\n // For ranges that span more than two values, we have to fill in the values.\n $range = range($current_value + 1, $current_value - $val - 1);\n $uncompressed_array = array_merge($uncompressed_array, $range);\n }\n // Add the step value to the $current_value\n $current_value += abs($val); \n // Add the newly-determined $current_value to our list. If $val==0, it is a repeat!\n array_push($uncompressed_array, $current_value); \n }\n\n // Display the uncompressed array.\n echo \"<hr>Reconstituted Array has \"\n .count($uncompressed_array).' elements: '\n .implode(', ',$uncompressed_array).\n '<hr>';\n --------------------------------------------------------------------------------\nOriginal Array has 63 elements: {not showing, since I modified the original array directly}\nCompressed Array has 53 elements: -40, 4, -1, 6, -1, 3, 2, 2, 0, 8, -1, 2, -1, 13, 3, 6, 2, 6, 0, 3, 2, -1, 8, -11, 5, 12, -1, 3, -1, 0, -1, 3, -1, 2, 7, 6, 5, 7, -1, 0, -1, 7, 4, 3, 2, 3, 2, 2, 2, 3, 8, 0, 4\nCompressed String has 110 characters: -40+4-1+6-1+3+2+2+0+8-1+2-1+13+3+6+2+6+0+3+2-1+8-11+5+12-1+3-1+0-1+3-1+2+7+6+5+7-1+0-1+7+4+3+2+3+2+2+2+3+8+0+4\nPacked String has 54 (some probably not printable) characters: cØÿÿÿÿ ÿõ ÿÿÿÿÿÿ\nBase64 String has 72 (all printable) characters: Y9gE/wb/AwICAAj/Av8NAwYCBgADAv8I9QUM/wP/AP8D/wIHBgUH/wD/BwQDAgMCAgIDCAAE\nGZipped String has 53 (some probably not printable) characters: xœ Ê» ÑÈί€)YšE¨MŠ“^qçºR¬m&Òõ‹%Ê&TFʉùÀ6ÿÁÁ Æ\nBase64 of GZipped String has 72 (all printable) characters: eJwNyrsNACAMA9HIzq+AKVmaRahNipNecee6UgSsBW0m0gj1iyXKJlRGjcqJ+cA2/8HBDcY=\n--------------------------------------------------------------------------------\nReconstituted Array has 63 elements: -40, -36, -35, -29, -28, -25, -23, -21, -21, -13, -12, -10, -9, 4, 7, 13, 15, 21, 21, 24, 26, 27, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 51, 63, 64, 67, 68, 68, 69, 72, 73, 75, 82, 88, 93, 100, 101, 101, 102, 109, 113, 116, 118, 121, 123, 125, 127, 130, 138, 138, 142\n--------------------------------------------------------------------------------\n"
},
{
"answer_id": 47189644,
"author": "Antithesis",
"author_id": 5949521,
"author_profile": "https://Stackoverflow.com/users/5949521",
"pm_score": 2,
"selected": false,
"text": "main=mapM_ print [x|x<-[1..160],x`notElem`[101..109]]\n $ runhaskell generator.hs >> data\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14316/"
] |
283,316
|
<p>I'm having a problem where a jQuery setting against an .html() property on a selected element is returning the error 'nodeName' is null or not an object. This only occurs on IE6 and IE7, but not FF2, FF3, Opera (latest Nov 12,2008) or Safari (again, latest).</p>
|
[
{
"answer_id": 283328,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "'nodeName' is null or not an object\n"
},
{
"answer_id": 283340,
"author": "Rob",
"author_id": 34224,
"author_profile": "https://Stackoverflow.com/users/34224",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
},
{
"answer_id": 5487368,
"author": "Oscar",
"author_id": 660432,
"author_profile": "https://Stackoverflow.com/users/660432",
"pm_score": 2,
"selected": false,
"text": "nodeName: function( elem, name ) {\n return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();\n},\n elem name elem elem elem .nodeName elem return elem && elem.nodeName && elem.nodeName.toUpperCase()...\n elem elem.nodeName elem"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,348
|
<p>I'm trying to use the Visitor Pattern and I have as follows:</p>
<pre><code>public class EnumerableActions<T> : IEnumerableActions<T>
{
private IEnumerable<T> itemsToActOn;
public EnumerableActions ( IEnumerable<T> itemsToActOn )
{
this.itemsToActOn = itemsToActOn;
}
public void VisitAllItemsUsing ( IVisitor<T> visitor )
{
foreach (T t in itemsToActOn)
{
visitor.Visit ( t );// after this, the item is unaffected.
}
}
</code></pre>
<p>The visitor :</p>
<pre><code>internal class TagMatchVisitor : IVisitor<Tag>
{
private readonly IList<Tag> _existingTags;
public TagMatchVisitor ( IList<Tag> existingTags )
{
_existingTags = existingTags;
}
#region Implementation of IVisitor<Tag>
public void Visit ( Tag newItem )
{
Tag foundTag = _existingTags.FirstOrDefault(tg => tg.TagName.Equals(newItem.TagName, StringComparison.OrdinalIgnoreCase));
if (foundTag != null)
newItem = foundTag; // replace the existing item with this one.
}
#endregion
}
</code></pre>
<p>And where I'm calling the visitor :</p>
<pre><code>IList<Tag> tags = ..get the list;
tags.VisitAllItemsUsing(new TagMatchVisitor(existingTags));
</code></pre>
<p>So .. where am I losing the reference ?
after newItem = foundTag - I expect that in the foreach in the visitor I would have the new value - obviously that's not happening.</p>
<p><strong>Edit</strong> I think I found the answer - in a foreach the variable is readonly.</p>
<p><a href="http://discuss.joelonsoftware.com/default.asp?dotnet.12.521767.19" rel="nofollow noreferrer">http://discuss.joelonsoftware.com/default.asp?dotnet.12.521767.19</a></p>
|
[
{
"answer_id": 283359,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "IList<T> for(int i = 0 ; i < itemsToActOn.Count ; i++)\n{\n T value = itemsToActOn[i];\n visitor.Visit(ref t)\n itemsToActOn[i] = value;\n}\n T Visit(T) for(int i = 0 ; i < itemsToActOn.Count ; i++)\n{\n itemsToActOn[i] = visitor.Visit(itemsToActOn[i]);\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5246/"
] |
283,350
|
<p>In Erlang, every process has a group leader, and when a process wants to print something (i.e. it calls the io library or does something similar), it will send a message to its group leader.</p>
<p>My question is, where can I find the specification of these messages? Or in general, the specification of what a group leader should do?</p>
<p>I managed to find out with some experimenting that sometimes the process sends an <code>{io_request, Sender, GroupLeader, Request}</code> term, and the answer is an <code>{io_reply, GroupLeader, ok}</code> term, but there may be other cases.</p>
|
[
{
"answer_id": 296496,
"author": "archaelus",
"author_id": 9040,
"author_profile": "https://Stackoverflow.com/users/9040",
"pm_score": 4,
"selected": true,
"text": " {io_request, From, ReplyAs, Request}\n %From is the process to send the reply to, \n %ReplyAs is any term the caller desires to \n %match up the request and the response. (returned verbatim in the reply)\n {io_reply, ReplyAs, Reply}\n {put_chars, IoList} % puts the iolist\n {put_chars, M,F,A} % puts the result of apply(M,F,A)\n {get_geometry, 'rows' | 'columns'} % returns the number of rows or columns of the console\n {get_line, Prompt} % calls io_lib:collect_line(Prompt)\n {get_chars, Prompt, Mod, Func, ExtraArgs} \n {get_until, Prompt, Mod, Func, Args}\n {setopts, Options} % only option supported by user is 'binary' \n % (binary mode if present in Options, list mode otherwise)\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17916/"
] |
283,374
|
<p>To recap for those .NET gurus who might not know the Java API:</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow noreferrer">ConcurrentHashMap</a> in Java has atomic methods (i.e. require no external locking) for common Map modification operations such as:</p>
<pre><code>putIfAbsent(K key, V value)
remove(Object key, Object value)
replace(K key, V value)
</code></pre>
<p>It also allows iteration over the keyset without locking (it takes a copy at the start of iteration) and <code>get()</code> operations can generally be interleaved with calls to <code>put()</code> without blocking (it uses fine grained lock striping <a href="http://en.wiktionary.org/wiki/IIRC" rel="nofollow noreferrer">IIRC</a>).</p>
<p>Anyway, my question is: <strong>does .NET have an equivalent Dictionary implementation?</strong></p>
<p>I guess more generally, I'd be keen to know if .NET has a more general set of thread safe collection libraries. Or concurrency utilities in general - equivalent to <a href="http://en.wikipedia.org/wiki/Doug_Lea" rel="nofollow noreferrer">Doug Lea</a>'s <code>java.util.concurrent</code> libraries.</p>
|
[
{
"answer_id": 283400,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "ConcurrentDictionary ConcurrentHashMap Mutex ManualResetEvent AutoResetEvent ReaderWriterLock Semaphore ReaderWriterLockSlim"
},
{
"answer_id": 283441,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "Monitor lock(...) ReaderWriterLockSlim"
},
{
"answer_id": 1993061,
"author": "Olmo",
"author_id": 38670,
"author_profile": "https://Stackoverflow.com/users/38670",
"pm_score": 4,
"selected": false,
"text": "public TValue GetOrAdd(\n TKey key,\n Func<TKey, TValue> valueFactory\n)\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] |
283,375
|
<p>Let's say I'm running a simple server and have <code>accept()</code>ed a connection from a client.</p>
<p>What is the best way to tell when the client has disconnected? Normally, a client is supposed to send a close command, but what if it disconnects manually or loses network connection altogether? How can the server detect or handle this?</p>
|
[
{
"answer_id": 1525680,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": " Try\n Clients.Client.Send(BufferByte)\n Catch verror As Exception\n BufferString = verror.ToString\n End Try\n If BufferString <> \"\" Then\n EventLog.Text &= \"User disconnected: \" + vbNewLine\n Clients.Close()\n End If\n"
},
{
"answer_id": 17665015,
"author": "user207421",
"author_id": 207421,
"author_profile": "https://Stackoverflow.com/users/207421",
"pm_score": 7,
"selected": false,
"text": "read()/recv()/recvXXX() write()/send()/sendXXX() errno/WSAGetLastError() ECONNRESET, ioctl() FIONREAD FIONREAD"
},
{
"answer_id": 17666336,
"author": "Galleon",
"author_id": 2585455,
"author_profile": "https://Stackoverflow.com/users/2585455",
"pm_score": -1,
"selected": false,
"text": "char buf;\nint length=recv(socket, &buf, 0, 0);\nint nError=WSAGetLastError();\nif(nError!=WSAEWOULDBLOCK&&nError!=0){\n return 0;\n} \nif (nError==0){\n if (length==0) return 0;\n}\n"
},
{
"answer_id": 46581848,
"author": "Anand Paul",
"author_id": 8718951,
"author_profile": "https://Stackoverflow.com/users/8718951",
"pm_score": -1,
"selected": false,
"text": "void ReceiveStream(void *threadid)\n{\n while(true)\n {\n while(ch==0)\n {\n char buffer[1024];\n int newData;\n newData = recv(thisSocket, buffer, sizeof(buffer), 0);\n if(newData>=0)\n {\n std::cout << buffer << std::endl;\n }\n else\n {\n std::cout << \"Client disconnected\" << std::endl;\n if (thisSocket)\n {\n #ifdef WIN32\n closesocket(thisSocket);\n WSACleanup();\n #endif\n #ifdef LINUX\n close(thisSocket);\n #endif\n }\n break;\n }\n }\n ch = 1;\n StartSocket();\n }\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4924/"
] |
283,377
|
<p>Consider the following signature in C#:</p>
<pre><code>double Divide(int numerator, int denominator);
</code></pre>
<p>Is there a performance difference between the following implementations?</p>
<pre><code>return (double)numerator / denominator;
return numerator / (double)denominator;
return (double)numerator / (double)denominator;
</code></pre>
<p>I'm assuming that both of the above return the same answer.</p>
<p>Have I missed any other equivalent solution?</p>
|
[
{
"answer_id": 283386,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "static double A(int numerator, int denominator)\n{ return (double)numerator / denominator; }\n\nstatic double B(int numerator, int denominator)\n{ return numerator / (double)denominator; }\n\nstatic double C(int numerator, int denominator)\n{ return (double)numerator / (double)denominator; }\n .method private hidebysig static float64 A(int32 numerator, int32 denominator) cil managed\n{\n .maxstack 8\n L_0000: ldarg.0 // pushes numerator onto the stack\n L_0001: conv.r8 // converts the value at the top of the stack to double\n L_0002: ldarg.1 // pushes denominator onto the stack\n L_0003: conv.r8 // converts the value at the top of the stack to double\n L_0004: div // pops two values, divides, and pushes the result\n L_0005: ret // pops the value from the top of the stack as the return value\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24874/"
] |
283,392
|
<p>At the moment I have a set of divs, generated dynamically by php and all having their ids starting with 'itembox', with a count number appended. I have a droppable garbage bin area on the page so that the user can delete an individual itembox by fdragging and dropping on to the bin.</p>
<p>My problem is that the droppable won't seem to activate when I drag the original, while it will function (perfectly) when I have helper: 'clone' set. Unfortunately, though, when dragging, the cloning function takes its clone from the first iteration of the itembox, no matter which itembox is actually dragged.</p>
<p>So I'm looking for a solution to either make the droppable accept an original or force the cloning function to take its clone from the itembox actually dragged.</p>
|
[
{
"answer_id": 283978,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 2,
"selected": true,
"text": "$('#mydroppable').droppable(\n{\n accept: function() { return true; },\n drop: function () { alert(\"Dropped!\"); }\n});\n"
},
{
"answer_id": 8167529,
"author": "Wikki",
"author_id": 460966,
"author_profile": "https://Stackoverflow.com/users/460966",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\n$(document).ready(function(){\n $('.srcfield').draggable({\n revert: true \n });\n\n $('#trash').droppable({\n accept : \".srcfield\",\n over: function(){\n $(this).removeClass('out').addClass('over');\n },`enter code here`\n out: function(){\n $(this).removeClass('over').addClass('out');\n },\n drop: function(ev, ui){\n //var answer = confirm('Delete this item?');\n var theTitle = $(ui.draggable).attr(\"title\");\n $(this).html(\"<u>\"+theTitle+\"</u><br/> is deleted!\");\n }\n });\n});\n</script>\n\n\n<body>\n <div id=\"trash\" class=\"out\">\n <span>Trash</span>\n </div>\n <div id=\"sourcefields\">\n <div class=\"srcfield\" title=\"First Name\"><span>First Name</span></div>\n <div class=\"srcfield\" title=\"Last Name\"><span>Last Name</span></div>\n <div class=\"srcfield\" title=\"Age\"><span>Age</span></div>\n </div>\n</body>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28527/"
] |
283,406
|
<p>What is the difference between <code>atan</code> and <code>atan2</code> in C++?</p>
|
[
{
"answer_id": 283408,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 8,
"selected": true,
"text": "std::atan2 std::atan"
},
{
"answer_id": 284624,
"author": "Laserallan",
"author_id": 11758,
"author_profile": "https://Stackoverflow.com/users/11758",
"pm_score": 5,
"selected": false,
"text": "atan2 atan(y / x) x"
},
{
"answer_id": 9640800,
"author": "bheks",
"author_id": 1260183,
"author_profile": "https://Stackoverflow.com/users/1260183",
"pm_score": 3,
"selected": false,
"text": "atan2(y, x) atan atan(p) atan2 atan2 atan atan2"
},
{
"answer_id": 12011762,
"author": "Mehrwolf",
"author_id": 1450656,
"author_profile": "https://Stackoverflow.com/users/1450656",
"pm_score": 9,
"selected": false,
"text": "tan(α) = sin(α) / cos(α)\n sin cos tan π/2 Quadrant Angle sin cos tan\n-------------------------------------------------\n I 0 < α < π/2 + + +\n II π/2 < α < π + - -\n III π < α < 3π/2 - - +\n IV 3π/2 < α < 2π - + -\n tan(α) atan() -π/2 <= atan() <= π/2 sin(α) / cos(α) atan2() sin(α) cos(α) π atan() atan2(y, x) y x v α y = v * sin(α)\nx = v * cos(α)\n y/x = tan(α)\n atan(y/x) atan2(y,x)"
},
{
"answer_id": 23666868,
"author": "Keugyeol",
"author_id": 1309708,
"author_profile": "https://Stackoverflow.com/users/1309708",
"pm_score": 5,
"selected": false,
"text": "atan atan2 atan2"
},
{
"answer_id": 42610044,
"author": "user3303328",
"author_id": 3303328,
"author_profile": "https://Stackoverflow.com/users/3303328",
"pm_score": 0,
"selected": false,
"text": "atan2(y,x) sqrt(x*x+y*y) hypot(y,x) atan(x) atan(y/x) atan2 x y x=0 atan2(y,x) y x"
},
{
"answer_id": 50977404,
"author": "user497884",
"author_id": 9975309,
"author_profile": "https://Stackoverflow.com/users/9975309",
"pm_score": 1,
"selected": false,
"text": "-pi atan2(y,x) pi -pi/2 atan(y/x) pi/2 0 2*pi 2*pi 0 2*pi System.out.println(Math.atan2(1,1)); //pi/4 in the 1st quarter\nSystem.out.println(Math.atan2(1,-1)); //(pi/4)+(pi/2)=3*(pi/4) in the 2nd quarter\n\nSystem.out.println(Math.atan2(-1,-1 ));//-3*(pi/4) and it is less than 0.\nSystem.out.println(Math.atan2(-1,-1)+2*Math.PI); //5(pi/4) in the 3rd quarter\n\nSystem.out.println(Math.atan2(-1,1 ));//-pi/4 and it is less than 0.\nSystem.out.println(Math.atan2(-1,1)+2*Math.PI); //7*(pi/4) in the 4th quarter\n\nSystem.out.println(Math.atan(1 ));//pi/4\nSystem.out.println(Math.atan(-1 ));//-pi/4\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
283,416
|
<p>PostgreSQL allows the creation of 'Partial Indexes' which are basically indexes with conditional predicates. <a href="http://www.postgresql.org/docs/8.2/static/indexes-partial.html" rel="nofollow noreferrer">http://www.postgresql.org/docs/8.2/static/indexes-partial.html</a> </p>
<p>While testing, I found that they are performing very well for a case where the query is accessing only certain 12 rows in a table with 120k rows. </p>
<p>But before we deploy this, are there any disadvantages or caveats we should be aware of?</p>
|
[
{
"answer_id": 388158,
"author": "cope360",
"author_id": 48044,
"author_profile": "https://Stackoverflow.com/users/48044",
"pm_score": 3,
"selected": false,
"text": "Orders order_status where order_status = 'New'"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21029/"
] |
283,417
|
<p>I have a toolstrip containing, among other things, a ToolStripComboBox and a ToolStripButton. I want to add a ContextMenuStrip to both of them, but I don't have direct access to the toolstrip or its other contents, so I can't set the context menu of the toolstrip.</p>
<p>Setting the ContextMenuStrip for the ToolStripComboBox is easy:</p>
<pre><code>myToolStripComboBox.ComboBox.ContextMenuStrip = myContextMenu;
</code></pre>
<p>but there's no obvious equivalent for the ToolStripButton. How do I add a ContextMenuStrip to a ToolStripButton?</p>
|
[
{
"answer_id": 354468,
"author": "AlexeyMK",
"author_id": 5021,
"author_profile": "https://Stackoverflow.com/users/5021",
"pm_score": 0,
"selected": false,
"text": "toolstrip myToolStripButton.Parent"
},
{
"answer_id": 1774863,
"author": "Jason D",
"author_id": 215962,
"author_profile": "https://Stackoverflow.com/users/215962",
"pm_score": 3,
"selected": true,
"text": "public class MyTextBox : ToolStripTextBox\n{\n ContextMenuStrip _contextMenuStrip;\n\n public ContextMenuStrip ContextMenuStrip\n {\n get { return _contextMenuStrip; }\n set { _contextMenuStrip = value; }\n }\n\n protected override void OnMouseDown(MouseEventArgs e)\n {\n if (e.Button == MouseButtons.Right)\n {\n if (_contextMenuStrip !=null)\n _contextMenuStrip.Show(Parent.PointToScreen(e.Location));\n }\n }\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
283,419
|
<p>I've written a batch execution framework and in it I want (in some scenarios) to load an assembly from the GAC where there may be multiple versions but I just want to load the <em>latest version</em>.<br>
Is this even possible?</p>
<p>TIA</p>
|
[
{
"answer_id": 283880,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 2,
"selected": false,
"text": "Assembly.LoadWithPartialName(string)"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36852/"
] |
283,431
|
<p>My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it.</p>
<p>However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the </p>
<blockquote>
<p>'foo.py' is not recognized as an internal or external command, operable
program or batch file.</p>
</blockquote>
<p>I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of.</p>
|
[
{
"answer_id": 283545,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 3,
"selected": true,
"text": "subprocess.Popen([r'C:\\Python2.5\\python.exe', r'C:\\path\\to\\foo.py'])\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
283,454
|
<p>I have been working with hibernate/JPA on JBoss for some months now and have one question that I can't find an answer or solution for.</p>
<p>It seems like when creating new entity beans I'm not able to do a query before I at least have called EntityManager.persist(entityBean), or else I get the following error:</p>
<p><code>TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing</code></p>
<p>An example:</p>
<pre><code>Job job = new Job();
Collection<Task> tasks = job.getTasks();
//entityManager.persist(job);
ActionPlan actionPlan = (ActionPlan) entityManager.createNamedQuery("ActionPlan.findByCommand").
setParameter("type", RunOperation.Install).getSingleResult();
Task task = Task.getTask(actionPlan);
task.setActionPlan(actionPlan);
tasks.add(task);
task.setJob(job);
</code></pre>
<p>My problem is that I can't call createNamedQuery without first persisting 'job' (the line that is commented out). ActionPlan has a relation to Job, but the NamedQuery (findByCommand) does not join on Job. What bothers me is that I need to persist Job in order to query the database, when the new created Job is not even interesting in this context.<br>
Moving the call to persist() to the end of the snippet yields the above mentioned error.</p>
<p>I'm aware that the object I'm working on is not persisted, but persisting makes it impossible to rollback if an error occurs.</p>
<p>I believe there is a solution for this, so if someone has the answer I would be very thankful. What am I missing?</p>
|
[
{
"answer_id": 283628,
"author": "Georgy Bolyuba",
"author_id": 4052,
"author_profile": "https://Stackoverflow.com/users/4052",
"pm_score": 2,
"selected": false,
"text": "Session sess = factory.openSession();\nTransaction tx;\ntry {\ntx = sess.beginTransaction();\n //do some work\n ...\n tx.commit();\n}\ncatch (Exception e) {\n if (tx!=null) tx.rollback();\n throw e;\n}\nfinally {\n sess.close();\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16152/"
] |
283,456
|
<p>Anyone know a good and effective way to search/match for a byte pattern in an byte[] array and then return the positions.</p>
<p>For example</p>
<pre><code>byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};
byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125}
</code></pre>
|
[
{
"answer_id": 283469,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": -1,
"selected": false,
"text": " [STAThread]\n static void Main(string[] args)\n {\n byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};\n byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125};\n string needle, haystack;\n\n unsafe \n {\n fixed(byte * p = pattern) {\n needle = new string((SByte *) p, 0, pattern.Length);\n } // fixed\n\n fixed (byte * p2 = toBeSearched) \n {\n haystack = new string((SByte *) p2, 0, toBeSearched.Length);\n } // fixed\n\n int i = haystack.IndexOf(needle, 0);\n System.Console.Out.WriteLine(i);\n }\n }\n"
},
{
"answer_id": 283596,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 4,
"selected": false,
"text": "class Program\n{\n public static void Main()\n {\n byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};\n\n byte[] toBeSearched = new byte[] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125};\n\n List<int> positions = SearchBytePattern(pattern, toBeSearched);\n\n foreach (var item in positions)\n {\n Console.WriteLine(\"Pattern matched at pos {0}\", item);\n }\n\n }\n\n static public List<int> SearchBytePattern(byte[] pattern, byte[] bytes)\n {\n List<int> positions = new List<int>();\n int patternLength = pattern.Length;\n int totalLength = bytes.Length;\n byte firstMatchByte = pattern[0];\n for (int i = 0; i < totalLength; i++)\n {\n if (firstMatchByte == bytes[i] && totalLength - i >= patternLength)\n {\n byte[] match = new byte[patternLength];\n Array.Copy(bytes, i, match, 0, patternLength);\n if (match.SequenceEqual<byte>(pattern))\n {\n positions.Add(i);\n i += patternLength - 1;\n }\n }\n }\n return positions;\n }\n}\n"
},
{
"answer_id": 283648,
"author": "Jb Evain",
"author_id": 36702,
"author_profile": "https://Stackoverflow.com/users/36702",
"pm_score": 6,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\n\nstatic class ByteArrayRocks\n{ \n static readonly int[] Empty = new int[0];\n\n public static int[] Locate (this byte[] self, byte[] candidate)\n {\n if (IsEmptyLocate(self, candidate))\n return Empty;\n\n var list = new List<int>();\n\n for (int i = 0; i < self.Length; i++)\n {\n if (!IsMatch(self, i, candidate))\n continue;\n\n list.Add(i);\n }\n\n return list.Count == 0 ? Empty : list.ToArray();\n }\n\n static bool IsMatch (byte[] array, int position, byte[] candidate)\n {\n if (candidate.Length > (array.Length - position))\n return false;\n\n for (int i = 0; i < candidate.Length; i++)\n if (array[position + i] != candidate[i])\n return false;\n\n return true;\n }\n\n static bool IsEmptyLocate (byte[] array, byte[] candidate)\n {\n return array == null\n || candidate == null\n || array.Length == 0\n || candidate.Length == 0\n || candidate.Length > array.Length;\n }\n\n static void Main()\n {\n var data = new byte[] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125 };\n var pattern = new byte[] { 12, 3, 5, 76, 8, 0, 6, 125 };\n\n foreach (var position in data.Locate(pattern))\n Console.WriteLine(position);\n }\n}\n solution [Locate]: 00:00:00.7714027\nsolution [FindAll]: 00:00:03.5404399\nsolution [SearchBytePattern]: 00:00:01.1105190\nsolution [MatchBytePattern]: 00:00:03.0658212\n"
},
{
"answer_id": 283662,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nclass C {\n\n public static void Main() {\n byte[] data = {0, 100, 0, 255, 100, 0, 100, 0, 255};\n byte[] pattern = {0, 255};\n foreach (int i in FindAll(data, pattern)) {\n Console.WriteLine(i);\n }\n }\n\n public static IEnumerable<int> FindAll(\n byte[] haystack,\n byte[] needle\n ) {\n // bytes <-> latin-1 conversion is lossless\n Encoding latin1 = Encoding.GetEncoding(\"iso-8859-1\");\n string sHaystack = latin1.GetString(haystack);\n string sNeedle = latin1.GetString(needle);\n for (Match m = Regex.Match(sHaystack, Regex.Escape(sNeedle));\n m.Success; m = m.NextMatch()) {\n yield return m.Index;\n }\n }\n}\n"
},
{
"answer_id": 283895,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 1,
"selected": false,
"text": " for (int i = 0; i < self.Length; i++) {\n if (!IsMatch (self, i, candidate))\n continue;\n\n list.Add (i);\n }\n i += candidate.Length -2; // -2 instead of -1 because the i++ will add the last index\n int validMatches = 0;\nif (!IsMatch (self, i, candidate, out validMatches))\n{\n i += validMatches - 1; // -1 because the i++ will do the last one\n continue;\n}\n static bool IsMatch (byte [] array, int position, byte [] candidate, out int numberOfValidMatches)\n{\n numberOfValidMatches = 0;\n if (candidate.Length > (array.Length - position))\n return false;\n\n for (i = 0; i < candidate.Length; i++)\n {\n if (array [position + i] != candidate [i])\n return false;\n numberOfValidMatches++; \n }\n\n return true;\n}\n"
},
{
"answer_id": 283935,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 1,
"selected": false,
"text": " for (int i = 0; i < self.Length; i++) {\n if (!IsMatch (self, i, candidate))\n continue;\n list.Add (i);\n }\n candidate for for (int i = 0, n = self.Length - candidate.Length + 1; i < n; ++i) {\n if (!IsMatch (self, i, candidate))\n continue;\n list.Add (i);\n }\n IsMatch"
},
{
"answer_id": 284026,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 1,
"selected": false,
"text": "public static List<Int32> LocateSubset(Byte[] superSet, Byte[] subSet)\n{\n if ((superSet == null) || (subSet == null))\n {\n throw new ArgumentNullException();\n }\n if ((superSet.Length < subSet.Length) || (superSet.Length == 0) || (subSet.Length == 0))\n {\n return new List<Int32>();\n }\n var result = new List<Int32>();\n Int32 currentIndex = 0;\n Int32 maxIndex = superSet.Length - subSet.Length;\n while (currentIndex < maxIndex)\n {\n Int32 matchCount = CountMatches(superSet, currentIndex, subSet);\n if (matchCount == subSet.Length)\n {\n result.Add(currentIndex);\n }\n currentIndex++;\n if (matchCount > 0)\n {\n currentIndex += matchCount - 1;\n }\n }\n return result;\n}\n\nprivate static Int32 CountMatches(Byte[] superSet, int startIndex, Byte[] subSet)\n{\n Int32 currentOffset = 0;\n while (currentOffset < subSet.Length)\n {\n if (superSet[startIndex + currentOffset] != subSet[currentOffset])\n {\n break;\n }\n currentOffset++;\n }\n return currentOffset;\n}\n currentIndex++;\n if (matchCount > 0)\n {\n currentIndex += matchCount - 1;\n }\n"
},
{
"answer_id": 284154,
"author": "Anders R",
"author_id": 36504,
"author_profile": "https://Stackoverflow.com/users/36504",
"pm_score": 1,
"selected": false,
"text": " private static int CountPatternMatches(byte[] pattern, byte[] bytes)\n {\n int counter = 0;\n\n for (int i = 0; i < bytes.Length; i++)\n {\n if (bytes[i] == pattern[0] && (i + pattern.Length) < bytes.Length)\n {\n for (int x = 1; x < pattern.Length; x++)\n {\n if (pattern[x] != bytes[x+i])\n {\n break;\n }\n\n if (x == pattern.Length -1)\n {\n counter++;\n i = i + pattern.Length;\n }\n }\n }\n }\n\n return counter;\n }\n"
},
{
"answer_id": 332667,
"author": "GoClimbColorado",
"author_id": 42239,
"author_profile": "https://Stackoverflow.com/users/42239",
"pm_score": 4,
"selected": false,
"text": "public static List<int> IndexOfSequence(this byte[] buffer, byte[] pattern, int startIndex) \n{\n List<int> positions = new List<int>();\n int i = Array.IndexOf<byte>(buffer, pattern[0], startIndex); \n while (i >= 0 && i <= buffer.Length - pattern.Length) \n {\n byte[] segment = new byte[pattern.Length];\n Buffer.BlockCopy(buffer, i, segment, 0, pattern.Length); \n if (segment.SequenceEqual<byte>(pattern))\n positions.Add(i);\n i = Array.IndexOf<byte>(buffer, pattern[0], i + 1);\n }\n return positions; \n}\n while i = Array.IndexOf<byte>(buffer, pattern[0], i + 1); i = Array.IndexOf<byte>(buffer, pattern[0], i + pattern.Length); byte[] pattern = new byte[] {1, 2};\nbyte[] toBeSearched = new byte[] { 1, 1, 2, 1, 12 };\n i = Array.IndexOf<byte>(buffer, pattern[0], i + pattern.Length); i = Array.IndexOf<byte>(buffer, pattern[0], i + 1);"
},
{
"answer_id": 1271069,
"author": "Steve Hiner",
"author_id": 10221,
"author_profile": "https://Stackoverflow.com/users/10221",
"pm_score": 1,
"selected": false,
"text": "private static void TestMethod()\n{\n Random rnd = new Random(DateTime.Now.Millisecond);\n string Pattern = \"-------------------------------65498495198498\";\n byte[] pattern = Encoding.ASCII.GetBytes(Pattern);\n\n byte[] testBytes;\n int count = 3;\n for (int i = 0; i < 100; i++)\n {\n StringBuilder TestString = new StringBuilder(2500);\n TestString.Append(Pattern);\n byte[] buf = new byte[1000];\n rnd.NextBytes(buf);\n TestString.Append(Encoding.ASCII.GetString(buf));\n TestString.Append(Pattern);\n rnd.NextBytes(buf);\n TestString.Append(Encoding.ASCII.GetString(buf));\n TestString.Append(Pattern);\n testBytes = Encoding.ASCII.GetBytes(TestString.ToString());\n\n List<int> idx = IndexOfSequence(ref testBytes, pattern, 0);\n if (idx.Count != count)\n {\n Console.Write(\"change from {0} to {1} on iteration {2}: \", count, idx.Count, i);\n foreach (int ix in idx)\n {\n Console.Write(\"{0}, \", ix);\n }\n Console.WriteLine();\n count = idx.Count;\n }\n }\n\n Console.WriteLine(\"Press ENTER to exit\");\n Console.ReadLine();\n}\n change from 3 to 2 on iteration 1: 0, 2090,\nchange from 2 to 3 on iteration 2: 0, 1045, 2090,\nchange from 3 to 2 on iteration 3: 0, 1045,\nchange from 2 to 3 on iteration 4: 0, 1045, 2090,\nchange from 3 to 2 on iteration 6: 0, 2090,\nchange from 2 to 3 on iteration 7: 0, 1045, 2090,\nchange from 3 to 2 on iteration 11: 0, 2090,\nchange from 2 to 3 on iteration 12: 0, 1045, 2090,\nchange from 3 to 2 on iteration 14: 0, 2090,\nchange from 2 to 3 on iteration 16: 0, 1045, 2090,\nchange from 3 to 2 on iteration 17: 0, 1045,\nchange from 2 to 3 on iteration 18: 0, 1045, 2090,\nchange from 3 to 1 on iteration 20: 0,\nchange from 1 to 3 on iteration 21: 0, 1045, 2090,\nchange from 3 to 2 on iteration 22: 0, 2090,\nchange from 2 to 3 on iteration 23: 0, 1045, 2090,\nchange from 3 to 2 on iteration 24: 0, 2090,\nchange from 2 to 3 on iteration 25: 0, 1045, 2090,\nchange from 3 to 2 on iteration 26: 0, 2090,\nchange from 2 to 3 on iteration 27: 0, 1045, 2090,\nchange from 3 to 2 on iteration 43: 0, 1045,\nchange from 2 to 3 on iteration 44: 0, 1045, 2090,\nchange from 3 to 2 on iteration 48: 0, 1045,\nchange from 2 to 3 on iteration 49: 0, 1045, 2090,\nchange from 3 to 2 on iteration 50: 0, 2090,\nchange from 2 to 3 on iteration 52: 0, 1045, 2090,\nchange from 3 to 2 on iteration 54: 0, 1045,\nchange from 2 to 3 on iteration 57: 0, 1045, 2090,\nchange from 3 to 2 on iteration 62: 0, 1045,\nchange from 2 to 3 on iteration 63: 0, 1045, 2090,\nchange from 3 to 2 on iteration 72: 0, 2090,\nchange from 2 to 3 on iteration 73: 0, 1045, 2090,\nchange from 3 to 2 on iteration 75: 0, 2090,\nchange from 2 to 3 on iteration 76: 0, 1045, 2090,\nchange from 3 to 2 on iteration 78: 0, 1045,\nchange from 2 to 3 on iteration 79: 0, 1045, 2090,\nchange from 3 to 2 on iteration 81: 0, 2090,\nchange from 2 to 3 on iteration 82: 0, 1045, 2090,\nchange from 3 to 2 on iteration 85: 0, 2090,\nchange from 2 to 3 on iteration 86: 0, 1045, 2090,\nchange from 3 to 2 on iteration 89: 0, 2090,\nchange from 2 to 3 on iteration 90: 0, 1045, 2090,\nchange from 3 to 2 on iteration 91: 0, 2090,\nchange from 2 to 1 on iteration 92: 0,\nchange from 1 to 3 on iteration 93: 0, 1045, 2090,\nchange from 3 to 1 on iteration 99: 0,\n"
},
{
"answer_id": 1807740,
"author": "Sorin S.",
"author_id": 219941,
"author_profile": "https://Stackoverflow.com/users/219941",
"pm_score": 1,
"selected": false,
"text": " static public int SearchBytePattern(byte[] pattern, byte[] bytes)\n {\n int matches = 0;\n for (int i = 0; i < bytes.Length; i++)\n {\n if (pattern[0] == bytes[i] && bytes.Length - i >= pattern.Length)\n {\n bool ismatch = true;\n for (int j = 1; j < pattern.Length && ismatch == true; j++)\n {\n if (bytes[i + j] != pattern[j])\n ismatch = false;\n }\n if (ismatch)\n {\n matches++;\n i += pattern.Length - 1;\n }\n }\n }\n return matches;\n }\n"
},
{
"answer_id": 5227131,
"author": "Foubar",
"author_id": 649008,
"author_profile": "https://Stackoverflow.com/users/649008",
"pm_score": 2,
"selected": false,
"text": " public static unsafe long IndexOf(this byte[] Haystack, byte[] Needle)\n {\n fixed (byte* H = Haystack) fixed (byte* N = Needle)\n {\n long i = 0;\n for (byte* hNext = H, hEnd = H + Haystack.LongLength; hNext < hEnd; i++, hNext++)\n {\n bool Found = true;\n for (byte* hInc = hNext, nInc = N, nEnd = N + Needle.LongLength; Found && nInc < nEnd; Found = *nInc == *hInc, nInc++, hInc++) ;\n if (Found) return i;\n }\n return -1;\n }\n }\n public static unsafe List<long> IndexesOf(this byte[] Haystack, byte[] Needle)\n {\n List<long> Indexes = new List<long>();\n fixed (byte* H = Haystack) fixed (byte* N = Needle)\n {\n long i = 0;\n for (byte* hNext = H, hEnd = H + Haystack.LongLength; hNext < hEnd; i++, hNext++)\n {\n bool Found = true;\n for (byte* hInc = hNext, nInc = N, nEnd = N + Needle.LongLength; Found && nInc < nEnd; Found = *nInc == *hInc, nInc++, hInc++) ;\n if (Found) Indexes.Add(i);\n }\n return Indexes;\n }\n }\n"
},
{
"answer_id": 6568360,
"author": "Jay",
"author_id": 390720,
"author_profile": "https://Stackoverflow.com/users/390720",
"pm_score": 1,
"selected": false,
"text": " /// <summary>\n /// Matches a byte array to another byte array\n /// forwards or reverse\n /// </summary>\n /// <param name=\"a\">byte array</param>\n /// <param name=\"offset\">start offset</param>\n /// <param name=\"len\">max length</param>\n /// <param name=\"b\">byte array</param>\n /// <param name=\"direction\">to move each iteration</param>\n /// <returns>true if all bytes match, otherwise false</returns>\n internal static bool Matches(ref byte[] a, int offset, int len, ref byte[] b, int direction = 1)\n {\n #region Only Matched from offset Within a and b, could not differ, e.g. if you wanted to mach in reverse for only part of a in some of b that would not work\n //if (direction == 0) throw new ArgumentException(\"direction\");\n //for (; offset < len; offset += direction) if (a[offset] != b[offset]) return false;\n //return true;\n #endregion\n //Will match if b contains len of a and return a a index of positive value\n return IndexOfBytes(ref a, ref offset, len, ref b, len) != -1;\n }\n\n///Here is the Implementation code\n\n /// <summary>\n /// Swaps two integers without using a temporary variable\n /// </summary>\n /// <param name=\"a\"></param>\n /// <param name=\"b\"></param>\n internal static void Swap(ref int a, ref int b)\n {\n a ^= b;\n b ^= a;\n a ^= b;\n }\n\n /// <summary>\n /// Swaps two bytes without using a temporary variable\n /// </summary>\n /// <param name=\"a\"></param>\n /// <param name=\"b\"></param>\n internal static void Swap(ref byte a, ref byte b)\n {\n a ^= b;\n b ^= a;\n a ^= b;\n }\n\n /// <summary>\n /// Can be used to find if a array starts, ends spot Matches or compltely contains a sub byte array\n /// Set checkLength to the amount of bytes from the needle you want to match, start at 0 for forward searches start at hayStack.Lenght -1 for reverse matches\n /// </summary>\n /// <param name=\"a\">Needle</param>\n /// <param name=\"offset\">Start in Haystack</param>\n /// <param name=\"len\">Length of required match</param>\n /// <param name=\"b\">Haystack</param>\n /// <param name=\"direction\">Which way to move the iterator</param>\n /// <returns>Index if found, otherwise -1</returns>\n internal static int IndexOfBytes(ref byte[] needle, ref int offset, int checkLength, ref byte[] haystack, int direction = 1)\n {\n //If the direction is == 0 we would spin forever making no progress\n if (direction == 0) throw new ArgumentException(\"direction\");\n //Cache the length of the needle and the haystack, setup the endIndex for a reverse search\n int needleLength = needle.Length, haystackLength = haystack.Length, endIndex = 0, workingOffset = offset;\n //Allocate a value for the endIndex and workingOffset\n //If we are going forward then the bound is the haystackLength\n if (direction >= 1) endIndex = haystackLength;\n #region [Optomization - Not Required]\n //{\n\n //I though this was required for partial matching but it seems it is not needed in this form\n //workingOffset = needleLength - checkLength;\n //}\n #endregion\n else Swap(ref workingOffset, ref endIndex); \n #region [Optomization - Not Required]\n //{ \n //Otherwise we are going in reverse and the endIndex is the needleLength - checkLength \n //I though the length had to be adjusted but it seems it is not needed in this form\n //endIndex = needleLength - checkLength;\n //}\n #endregion\n #region [Optomized to above]\n //Allocate a value for the endIndex\n //endIndex = direction >= 1 ? haystackLength : needleLength - checkLength,\n //Determine the workingOffset\n //workingOffset = offset > needleLength ? offset : needleLength; \n //If we are doing in reverse swap the two\n //if (workingOffset > endIndex) Swap(ref workingOffset, ref endIndex);\n //Else we are going in forward direction do the offset is adjusted by the length of the check\n //else workingOffset -= checkLength;\n //Start at the checkIndex (workingOffset) every search attempt\n #endregion\n //Save the checkIndex (used after the for loop is done with it to determine if the match was checkLength long)\n int checkIndex = workingOffset;\n #region [For Loop Version]\n ///Optomized with while (single op)\n ///for (int checkIndex = workingOffset; checkIndex < endIndex; offset += direction, checkIndex = workingOffset)\n ///{\n ///Start at the checkIndex\n /// While the checkIndex < checkLength move forward\n /// If NOT (the needle at the checkIndex matched the haystack at the offset + checkIndex) BREAK ELSE we have a match continue the search \n /// for (; checkIndex < checkLength; ++checkIndex) if (needle[checkIndex] != haystack[offset + checkIndex]) break; else continue;\n /// If the match was the length of the check\n /// if (checkIndex == checkLength) return offset; //We are done matching\n ///}\n #endregion\n //While the checkIndex < endIndex\n while (checkIndex < endIndex)\n {\n for (; checkIndex < checkLength; ++checkIndex) if (needle[checkIndex] != haystack[offset + checkIndex]) break; else continue;\n //If the match was the length of the check\n if (checkIndex == checkLength) return offset; //We are done matching\n //Move the offset by the direction, reset the checkIndex to the workingOffset\n offset += direction; checkIndex = workingOffset; \n }\n //We did not have a match with the given options\n return -1;\n }\n"
},
{
"answer_id": 6964519,
"author": "Victor",
"author_id": 647559,
"author_profile": "https://Stackoverflow.com/users/647559",
"pm_score": 2,
"selected": false,
"text": "class Program {\n static void Main(string[] args) {\n byte[] text = new byte[] {12,3,5,76,8,0,6,125,23,36,43,76,125,56,34,234,12,4,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,123};\n byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};\n\n BoyerMoore tmpSearch = new BoyerMoore(pattern,text);\n\n Console.WriteLine(tmpSearch.Match());\n Console.ReadKey();\n }\n\n public class BoyerMoore {\n\n private static int ALPHABET_SIZE = 256;\n\n private byte[] text;\n private byte[] pattern;\n\n private int[] last;\n private int[] match;\n private int[] suffix;\n\n public BoyerMoore(byte[] pattern, byte[] text) {\n this.text = text;\n this.pattern = pattern;\n last = new int[ALPHABET_SIZE];\n match = new int[pattern.Length];\n suffix = new int[pattern.Length];\n }\n\n\n /**\n * Searches the pattern in the text.\n * returns the position of the first occurrence, if found and -1 otherwise.\n */\n public int Match() {\n // Preprocessing\n ComputeLast();\n ComputeMatch();\n\n // Searching\n int i = pattern.Length - 1;\n int j = pattern.Length - 1; \n while (i < text.Length) {\n if (pattern[j] == text[i]) {\n if (j == 0) { \n return i;\n }\n j--;\n i--;\n } \n else {\n i += pattern.Length - j - 1 + Math.Max(j - last[text[i]], match[j]);\n j = pattern.Length - 1;\n }\n }\n return -1; \n } \n\n\n /**\n * Computes the function last and stores its values in the array last.\n * last(Char ch) = the index of the right-most occurrence of the character ch\n * in the pattern; \n * -1 if ch does not occur in the pattern.\n */\n private void ComputeLast() {\n for (int k = 0; k < last.Length; k++) { \n last[k] = -1;\n }\n for (int j = pattern.Length-1; j >= 0; j--) {\n if (last[pattern[j]] < 0) {\n last[pattern[j]] = j;\n }\n }\n }\n\n\n /**\n * Computes the function match and stores its values in the array match.\n * match(j) = min{ s | 0 < s <= j && p[j-s]!=p[j]\n * && p[j-s+1]..p[m-s-1] is suffix of p[j+1]..p[m-1] }, \n * if such s exists, else\n * min{ s | j+1 <= s <= m \n * && p[0]..p[m-s-1] is suffix of p[j+1]..p[m-1] }, \n * if such s exists,\n * m, otherwise,\n * where p is the pattern and m is its length.\n */\n private void ComputeMatch() {\n /* Phase 1 */\n for (int j = 0; j < match.Length; j++) { \n match[j] = match.Length;\n } //O(m) \n\n ComputeSuffix(); //O(m)\n\n /* Phase 2 */\n //Uses an auxiliary array, backwards version of the KMP failure function.\n //suffix[i] = the smallest j > i s.t. p[j..m-1] is a prefix of p[i..m-1],\n //if there is no such j, suffix[i] = m\n\n //Compute the smallest shift s, such that 0 < s <= j and\n //p[j-s]!=p[j] and p[j-s+1..m-s-1] is suffix of p[j+1..m-1] or j == m-1}, \n // if such s exists,\n for (int i = 0; i < match.Length - 1; i++) {\n int j = suffix[i + 1] - 1; // suffix[i+1] <= suffix[i] + 1\n if (suffix[i] > j) { // therefore pattern[i] != pattern[j]\n match[j] = j - i;\n } \n else {// j == suffix[i]\n match[j] = Math.Min(j - i + match[i], match[j]);\n }\n }\n\n /* Phase 3 */\n //Uses the suffix array to compute each shift s such that\n //p[0..m-s-1] is a suffix of p[j+1..m-1] with j < s < m\n //and stores the minimum of this shift and the previously computed one.\n if (suffix[0] < pattern.Length) {\n for (int j = suffix[0] - 1; j >= 0; j--) {\n if (suffix[0] < match[j]) { match[j] = suffix[0]; }\n }\n {\n int j = suffix[0];\n for (int k = suffix[j]; k < pattern.Length; k = suffix[k]) {\n while (j < k) {\n if (match[j] > k) {\n match[j] = k;\n }\n j++;\n }\n }\n }\n }\n }\n\n\n /**\n * Computes the values of suffix, which is an auxiliary array, \n * backwards version of the KMP failure function.\n * \n * suffix[i] = the smallest j > i s.t. p[j..m-1] is a prefix of p[i..m-1],\n * if there is no such j, suffix[i] = m, i.e. \n\n * p[suffix[i]..m-1] is the longest prefix of p[i..m-1], if suffix[i] < m.\n */\n private void ComputeSuffix() { \n suffix[suffix.Length-1] = suffix.Length; \n int j = suffix.Length - 1;\n for (int i = suffix.Length - 2; i >= 0; i--) { \n while (j < suffix.Length - 1 && !pattern[j].Equals(pattern[i])) {\n j = suffix[j + 1] - 1;\n }\n if (pattern[j] == pattern[i]) { \n j--; \n }\n suffix[i] = j + 1;\n }\n }\n\n }\n\n}\n"
},
{
"answer_id": 10140221,
"author": "Ravi",
"author_id": 1330682,
"author_profile": "https://Stackoverflow.com/users/1330682",
"pm_score": 0,
"selected": false,
"text": "private static int findMatch(byte[] data, byte[] pattern) {\n if(pattern.length > data.length){\n return -1;\n }\n for(int i = 0; i<data.length ;){\n int j;\n for(j=0;j<pattern.length;j++){\n\n if(pattern[j]!=data[i])\n break;\n i++;\n }\n if(j==pattern.length){\n System.out.println(\"Pattern found at : \"+(i - pattern.length ));\n return i - pattern.length ;\n }\n if(j!=0)continue;\n i++;\n }\n\n return -1;\n}\n"
},
{
"answer_id": 11866989,
"author": "Matten",
"author_id": 524475,
"author_profile": "https://Stackoverflow.com/users/524475",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Searches in the haystack array for the given needle using the default equality operator and returns the index at which the needle starts.\n/// </summary>\n/// <typeparam name=\"T\">Type of the arrays.</typeparam>\n/// <param name=\"haystack\">Sequence to operate on.</param>\n/// <param name=\"needle\">Sequence to search for.</param>\n/// <returns>Index of the needle within the haystack or -1 if the needle isn't contained.</returns>\npublic static IEnumerable<int> IndexOf<T>(this T[] haystack, T[] needle)\n{\n if ((needle != null) && (haystack.Length >= needle.Length))\n {\n for (int l = 0; l < haystack.Length - needle.Length + 1; l++)\n {\n if (!needle.Where((data, index) => !haystack[l + index].Equals(data)).Any())\n {\n yield return l;\n }\n }\n }\n}\n"
},
{
"answer_id": 14712207,
"author": "YujiSoftware",
"author_id": 1932017,
"author_profile": "https://Stackoverflow.com/users/1932017",
"pm_score": 5,
"selected": false,
"text": "public static IEnumerable<int> PatternAt(byte[] source, byte[] pattern)\n{\n for (int i = 0; i < source.Length; i++)\n {\n if (source.Skip(i).Take(pattern.Length).SequenceEqual(pattern))\n {\n yield return i;\n }\n }\n}\n"
},
{
"answer_id": 20557026,
"author": "ApeShoes",
"author_id": 3097613,
"author_profile": "https://Stackoverflow.com/users/3097613",
"pm_score": 0,
"selected": false,
"text": " static void Main(string[] args)\n {\n // 1 1 1 1 1 1 1 1 1 1 2 2 2\n // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9\n byte[] buffer = new byte[] { 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 5, 5, 0, 5, 5, 1, 2 };\n byte[] beginPattern = new byte[] { 1, 0, 2 };\n byte[] middlePattern = new byte[] { 8, 9, 10 };\n byte[] endPattern = new byte[] { 9, 10, 11 };\n byte[] wholePattern = new byte[] { 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };\n byte[] noMatchPattern = new byte[] { 7, 7, 7 };\n\n int beginIndex = ByteArrayPatternIndex(buffer, beginPattern);\n int middleIndex = ByteArrayPatternIndex(buffer, middlePattern);\n int endIndex = ByteArrayPatternIndex(buffer, endPattern);\n int wholeIndex = ByteArrayPatternIndex(buffer, wholePattern);\n int noMatchIndex = ByteArrayPatternIndex(buffer, noMatchPattern);\n }\n\n /// <summary>\n /// Returns the index of the first occurrence of a byte array within another byte array\n /// </summary>\n /// <param name=\"buffer\">The byte array to be searched</param>\n /// <param name=\"pattern\">The byte array that contains the pattern to be found</param>\n /// <returns>If buffer contains pattern then the index of the first occurrence of pattern within buffer; otherwise, -1</returns>\n public static int ByteArrayPatternIndex(byte[] buffer, byte[] pattern)\n {\n if (buffer != null && pattern != null && pattern.Length <= buffer.Length)\n {\n int resumeIndex;\n for (int i = 0; i <= buffer.Length - pattern.Length; i++)\n {\n if (buffer[i] == pattern[0]) // Current byte equals first byte of pattern\n {\n resumeIndex = 0;\n for (int x = 1; x < pattern.Length; x++)\n {\n if (buffer[i + x] == pattern[x])\n {\n if (x == pattern.Length - 1) // Matched the entire pattern\n return i;\n else if (resumeIndex == 0 && buffer[i + x] == pattern[0]) // The current byte equals the first byte of the pattern so start here on the next outer loop iteration\n resumeIndex = i + x;\n }\n else\n {\n if (resumeIndex > 0)\n i = resumeIndex - 1; // The outer loop iterator will increment so subtract one\n else if (x > 1)\n i += (x - 1); // Advance the outer loop variable since we already checked these bytes\n break;\n }\n }\n }\n }\n }\n return -1;\n }\n\n /// <summary>\n /// Returns the indexes of each occurrence of a byte array within another byte array\n /// </summary>\n /// <param name=\"buffer\">The byte array to be searched</param>\n /// <param name=\"pattern\">The byte array that contains the pattern to be found</param>\n /// <returns>If buffer contains pattern then the indexes of the occurrences of pattern within buffer; otherwise, null</returns>\n /// <remarks>A single byte in the buffer array can only be part of one match. For example, if searching for 1,2,1 in 1,2,1,2,1 only zero would be returned.</remarks>\n public static int[] ByteArrayPatternIndex(byte[] buffer, byte[] pattern)\n {\n if (buffer != null && pattern != null && pattern.Length <= buffer.Length)\n {\n List<int> indexes = new List<int>();\n int resumeIndex;\n for (int i = 0; i <= buffer.Length - pattern.Length; i++)\n {\n if (buffer[i] == pattern[0]) // Current byte equals first byte of pattern\n {\n resumeIndex = 0;\n for (int x = 1; x < pattern.Length; x++)\n {\n if (buffer[i + x] == pattern[x])\n {\n if (x == pattern.Length - 1) // Matched the entire pattern\n indexes.Add(i);\n else if (resumeIndex == 0 && buffer[i + x] == pattern[0]) // The current byte equals the first byte of the pattern so start here on the next outer loop iteration\n resumeIndex = i + x;\n }\n else\n {\n if (resumeIndex > 0)\n i = resumeIndex - 1; // The outer loop iterator will increment so subtract one\n else if (x > 1)\n i += (x - 1); // Advance the outer loop variable since we already checked these bytes\n break;\n }\n }\n }\n }\n if (indexes.Count > 0)\n return indexes.ToArray();\n }\n return null;\n }\n"
},
{
"answer_id": 31107925,
"author": "Dylan Nicholson",
"author_id": 2006109,
"author_profile": "https://Stackoverflow.com/users/2006109",
"pm_score": 2,
"selected": false,
"text": "public static unsafe long IndexOf(this byte[] haystack, byte[] needle, long startOffset = 0)\n{ \n fixed (byte* h = haystack) fixed (byte* n = needle)\n {\n for (byte* hNext = h + startOffset, hEnd = h + haystack.LongLength + 1 - needle.LongLength, nEnd = n + needle.LongLength; hNext < hEnd; hNext++)\n for (byte* hInc = hNext, nInc = n; *nInc == *hInc; hInc++)\n if (++nInc == nEnd)\n return hNext - h;\n return -1;\n }\n}\n"
},
{
"answer_id": 38048468,
"author": "eocron",
"author_id": 5639688,
"author_profile": "https://Stackoverflow.com/users/5639688",
"pm_score": 2,
"selected": false,
"text": "var oregex = new ORegex<byte>(\"{0}{1}{2}\", x=> x==12, x=> x==3, x=> x==5);\nvar toSearch = new byte[]{1,1,12,3,5,1,12,3,5,5,5,5};\n\nvar found = oregex.Matches(toSearch);\n i:2;l:3\ni:6;l:3\n"
},
{
"answer_id": 38625726,
"author": "Ing. Gerardo Sánchez",
"author_id": 4685116,
"author_profile": "https://Stackoverflow.com/users/4685116",
"pm_score": 5,
"selected": false,
"text": "int Search(byte[] src, byte[] pattern)\n{\n int maxFirstCharSlot = src.Length - pattern.Length + 1;\n for (int i = 0; i < maxFirstCharSlot; i++)\n {\n if (src[i] != pattern[0]) // compare only first byte\n continue;\n \n // found a match on first byte, now try to match rest of the pattern\n for (int j = pattern.Length - 1; j >= 1; j--) \n {\n if (src[i + j] != pattern[j]) break;\n if (j == 1) return i;\n }\n }\n return -1;\n}\n"
},
{
"answer_id": 41414219,
"author": "Mehmet",
"author_id": 6250518,
"author_profile": "https://Stackoverflow.com/users/6250518",
"pm_score": 0,
"selected": false,
"text": "public int Search3(byte[] src, byte[] pattern)\n {\n int index = -1;\n\n for (int i = 0; i < src.Length; i++)\n {\n if (src[i] != pattern[0])\n {\n continue;\n }\n else\n {\n bool isContinoue = true;\n for (int j = 1; j < pattern.Length; j++)\n {\n if (src[++i] != pattern[j])\n {\n isContinoue = true;\n break;\n }\n if(j == pattern.Length - 1)\n {\n isContinoue = false;\n }\n }\n if ( ! isContinoue)\n {\n index = i-( pattern.Length-1) ;\n break;\n }\n }\n }\n return index;\n }\n"
},
{
"answer_id": 51892503,
"author": "Codehack",
"author_id": 2513355,
"author_profile": "https://Stackoverflow.com/users/2513355",
"pm_score": 0,
"selected": false,
"text": " public unsafe int IndexOfPattern(byte[] src, byte[] pattern)\n {\n fixed(byte *srcPtr = &src[0])\n fixed (byte* patternPtr = &pattern[0])\n {\n for (int x = 0; x < src.Length; x++)\n {\n byte currentValue = *(srcPtr + x);\n\n if (currentValue != *patternPtr) continue;\n\n bool match = false;\n\n for (int y = 0; y < pattern.Length; y++)\n {\n byte tempValue = *(srcPtr + x + y);\n if (tempValue != *(patternPtr + y))\n {\n match = false;\n break;\n }\n\n match = true;\n }\n\n if (match)\n return x;\n }\n }\n return -1;\n }\n public int IndexOfPatternSafe(byte[] src, byte[] pattern)\n {\n for (int x = 0; x < src.Length; x++)\n {\n byte currentValue = src[x];\n if (currentValue != pattern[0]) continue;\n\n bool match = false;\n\n for (int y = 0; y < pattern.Length; y++)\n {\n byte tempValue = src[x + y];\n if (tempValue != pattern[y])\n {\n match = false;\n break;\n }\n\n match = true;\n }\n\n if (match)\n return x;\n }\n\n return -1;\n }\n"
},
{
"answer_id": 56125234,
"author": "spludlow",
"author_id": 8815031,
"author_profile": "https://Stackoverflow.com/users/8815031",
"pm_score": 0,
"selected": false,
"text": " public static long FindBinaryPattern(byte[] data, byte[] pattern)\n {\n using (MemoryStream stream = new MemoryStream(data))\n {\n return FindBinaryPattern(stream, pattern);\n }\n }\n public static long FindBinaryPattern(string filename, byte[] pattern)\n {\n using (FileStream stream = new FileStream(filename, FileMode.Open))\n {\n return FindBinaryPattern(stream, pattern);\n }\n }\n public static long FindBinaryPattern(Stream stream, byte[] pattern)\n {\n byte[] buffer = new byte[1024 * 1024];\n int patternIndex = 0;\n int read;\n while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)\n {\n for (int bufferIndex = 0; bufferIndex < read; ++bufferIndex)\n {\n if (buffer[bufferIndex] == pattern[patternIndex])\n {\n ++patternIndex;\n if (patternIndex == pattern.Length)\n return stream.Position - (read - bufferIndex) - pattern.Length + 1;\n }\n else\n {\n patternIndex = 0;\n }\n }\n }\n return -1;\n }\n"
},
{
"answer_id": 58347430,
"author": "Kevinoid",
"author_id": 503410,
"author_profile": "https://Stackoverflow.com/users/503410",
"pm_score": 3,
"selected": false,
"text": "MemoryExtensions.IndexOf Span int matchIndex = toBeSearched.AsSpan().IndexOf(pattern);\n public static IEnumerable<int> IndexesOf(this byte[] haystack, byte[] needle,\n int startIndex = 0, bool includeOverlapping = false)\n{\n int matchIndex = haystack.AsSpan(startIndex).IndexOf(needle);\n while (matchIndex >= 0)\n {\n yield return startIndex + matchIndex;\n startIndex += matchIndex + (includeOverlapping ? 1 : needle.Length);\n matchIndex = haystack.AsSpan(startIndex).IndexOf(needle);\n }\n}\n"
},
{
"answer_id": 70309679,
"author": "Philipp Schumacher",
"author_id": 8712203,
"author_profile": "https://Stackoverflow.com/users/8712203",
"pm_score": 0,
"selected": false,
"text": "void Main()\n{\n Console.WriteLine(new[]{255,1,3,4,8,99,92,9,0,5,128}.Position(new[]{9,0}));\n \n Console.WriteLine(\"Philipp\".ToArray().Position(\"il\".ToArray()));\n\n Console.WriteLine(new[] { \"Mo\", \"Di\", \"Mi\", \"Do\", \"Fr\", \"Sa\", \"So\",\"Mo\", \"Di\", \"Mi\", \"Do\", \"Fr\", \"Sa\", \"So\"}.Position(new[] { \"Fr\", \"Sa\" }, 7));\n}\n\nstatic class Extensions\n{\n public static int Position<T>(this T[] source, T[] pattern, int start = 0)\n {\n var matchLenght = 0;\n foreach (var indexSource in Enumerable.Range(start, source.Length - pattern.Length))\n foreach (var indexPattern in Enumerable.Range(0, pattern.Length))\n if (source[indexSource + indexPattern].Equals(pattern[indexPattern]))\n if (++matchLenght == pattern.Length)\n return indexSource;\n return -1;\n }\n}\n 7\n2\n11\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36504/"
] |
283,460
|
<p>While connecting .NET to sybase server I got this error message:</p>
<blockquote>
<p>[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified</p>
</blockquote>
<p>This has worked properly before. System DSN with same details worked and data connection through vs.net also worked.</p>
<p>I am using VS.NET 2005.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 292261,
"author": "user37887",
"author_id": 37887,
"author_profile": "https://Stackoverflow.com/users/37887",
"pm_score": -1,
"selected": false,
"text": "regedit HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC"
},
{
"answer_id": 5034297,
"author": "SqlRyan",
"author_id": 8114,
"author_profile": "https://Stackoverflow.com/users/8114",
"pm_score": 5,
"selected": false,
"text": "%windir%\\SysWOW64\\odbcad32.exe (%windir% is usually C:\\Windows)\n"
},
{
"answer_id": 40742152,
"author": "Withnail",
"author_id": 1293222,
"author_profile": "https://Stackoverflow.com/users/1293222",
"pm_score": 0,
"selected": false,
"text": "Control Panel > ODBC Drivers > New"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,464
|
<p>Is there any such thing as a virtual Lineprinter.I mean a software emulation of a printer, that outputs to screen.</p>
<p>I have a project to change the output of print job. My past experience with a lineprinter was tedious rounds of</p>
<pre><code>loop:
print
walk down two flights
check the output
walk back up two flights
edit code
got loop:
</code></pre>
<p>Anyone who thinks a lineprinter can be installed in a programmers office has not used a LinePrinter!</p>
<p>Googles just turning up printer emulation, as in printers that emulate other printers or virtual printer ports!</p>
|
[
{
"answer_id": 292261,
"author": "user37887",
"author_id": 37887,
"author_profile": "https://Stackoverflow.com/users/37887",
"pm_score": -1,
"selected": false,
"text": "regedit HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC"
},
{
"answer_id": 5034297,
"author": "SqlRyan",
"author_id": 8114,
"author_profile": "https://Stackoverflow.com/users/8114",
"pm_score": 5,
"selected": false,
"text": "%windir%\\SysWOW64\\odbcad32.exe (%windir% is usually C:\\Windows)\n"
},
{
"answer_id": 40742152,
"author": "Withnail",
"author_id": 1293222,
"author_profile": "https://Stackoverflow.com/users/1293222",
"pm_score": 0,
"selected": false,
"text": "Control Panel > ODBC Drivers > New"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15710/"
] |
283,465
|
<p>What's your preferred way of wrapping lines of code, especially when it comes to long argument lists?</p>
<p>There has been several questions relating to wrapping lines (such as <a href="https://stackoverflow.com/questions/268284/when-writing-code-do-you-wrap-text-or-not">When writing code do you wrap text or not?</a> and <a href="https://stackoverflow.com/questions/276022/line-width-formatting-standard">Line width formatting standard</a>), but I haven't been able to find one which covers where to wrap a line of code.</p>
<p>Let's say we have a line of code that keeps going and going like this example:</p>
<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, Argument3, Argument4);
</code></pre>
<p><strong>How should that be wrapped?</strong></p>
<p>Here's a few ways I can think of, and some of their downsides:</p>
<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2,
Argument3, Argument4);
</code></pre>
<p>I personally don't prefer that option because the formatting seems to visually separate the argument list from the method I am trying to call, especially since there is an assignment equals sign ("=") right above the orphanged arguments on the new line.</p>
<p>So, for a while I went with the following approach:</p>
<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1,
Argument2,
Argument3,
Argument4);
</code></pre>
<p>Here, the arguments are all bundled together, all on the side of the method's first argument. However, one catch is that the argument list won't always line up in the second line onwards because of the number of spaces that the tab indents. (And typing extra spaces for formatting would be too time consuming.)</p>
<p>An <a href="https://stackoverflow.com/questions/268284/when-writing-code-do-you-wrap-text-or-not#269025">answer</a> in the one of the previous questions suggested the following format:</p>
<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(
Argument1,
Argument2,
Argument3,
Argument4
);
</code></pre>
<p>I actually like this format, due to its visual appeal, but it also it does visually separate the arguments from the method that the list belongs to. Also, I prefer to have a single method call not take up too many lines.</p>
<p>So, my question is, <em>without getting into the issue of preventing a code of line from getting too long in the first place</em>, <strong>how would you recommend wrapping lines of code?</strong> Specifically, <strong>where is a good place to break a line of code, when it comes to long argument lists?</strong></p>
|
[
{
"answer_id": 283483,
"author": "Dheer",
"author_id": 17266,
"author_profile": "https://Stackoverflow.com/users/17266",
"pm_score": 4,
"selected": false,
"text": "int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1,\n Argument2,\n Argument3,\n Argument4\n);\n int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1, Argument2, Argument3, Argument4,\n Argument005, Argument006, Argument7, Argument8\n);\n"
},
{
"answer_id": 283493,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 0,
"selected": false,
"text": "int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1,\n Argument2,\n Argument3,\n Argument4);\n int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2,\n Argument3, Argument4);\n"
},
{
"answer_id": 283578,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 4,
"selected": false,
"text": "int SomeReturnValue = SomeMethodWithLotsOfArguments\n( Argument1,\n Argument2,\n Argument3,\n Argument4\n);\n"
},
{
"answer_id": 283647,
"author": "Inshallah",
"author_id": 36862,
"author_profile": "https://Stackoverflow.com/users/36862",
"pm_score": 1,
"selected": false,
"text": "SomeVeryVerboseTypeName SomeReturnValue\n = SomeMethodWithLotsOfArguments(Argument1, Argument2, ...);\n"
},
{
"answer_id": 283670,
"author": "bendin",
"author_id": 33412,
"author_profile": "https://Stackoverflow.com/users/33412",
"pm_score": 1,
"selected": false,
"text": "int SomeReturnValue =\n SomeMethodWithLotsOfArguments(Argument1, Argument2, ...);\n int SomeReturnValue = SomeMethodWithLotsOfArguments\n (Argument1, Argument2, ... );\n int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1, Argument2, ... );\n int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1, \n Argument2,\n);\n"
},
{
"answer_id": 283818,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 3,
"selected": false,
"text": "int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, \n Argument3, Argument4);\n int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1 + Expression1 + Expression2, \n Argument2 - Expression3 * Expression4, \n Argument3, \n Argument4 * Expression5 + Expression6 - Expression7);\n"
},
{
"answer_id": 283846,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 1,
"selected": false,
"text": "int a = foo(a + b,\n c + d);\n"
},
{
"answer_id": 283876,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 3,
"selected": false,
"text": "int SomeReturnValue \n = SomeMethodWithLotsOfArguments(\n Argument1\n , Argument2\n , Argument3\n , Argument4\n );\n"
},
{
"answer_id": 283948,
"author": "MikeJ",
"author_id": 10676,
"author_profile": "https://Stackoverflow.com/users/10676",
"pm_score": 1,
"selected": false,
"text": "someStruct.x = somevalue;\nsomestruct.y = someothervalue;\n\nint someResturnValue - SomeMethod(somestruct);\n"
},
{
"answer_id": 24954701,
"author": "Abdillah",
"author_id": 1391782,
"author_profile": "https://Stackoverflow.com/users/1391782",
"pm_score": 1,
"selected": false,
"text": "int variable_with_really_long_name = functionWhichDoMore(Argument1, ArgumentA2, \n ArgumentA3, Argument4, \n ArgumentA5, Argument6);\n int variable_with_really_long_name = somefunctionWhichDoMore(Argument_Expand1, \n Argument2, \n Argument_Expand3, \n Argument_Expand4, \n Argument_Expand5, \n Argument6);\n int variable_with_really_long_name = someFunctionWhichDoMore\n (\n Argument_Expand_More1, \n Argument_Expand_More2, \n Argument_Expand3, Argument4, \n Argument_Expand_More5, Argument6\n );\n !(so_ugly)"
},
{
"answer_id": 25313265,
"author": "Gio",
"author_id": 3200088,
"author_profile": "https://Stackoverflow.com/users/3200088",
"pm_score": 0,
"selected": false,
"text": "int variable_with_really_long_name = functionWhichDoMore(\n Argument1, ArgumentA2, ArgumentA3, Argument4, \n ArgumentA5, Argument6);\n\nint i = foo(Argument1, ArgumentA2, ArgumentA3, Argument4, \n ArgumentA5, Argument6);\n int variable_with_really_long_name = functionWhichDoMore(arg1,\n arg2)\n int variable_with_really_long_name = functionWhichDoMore(arg1, arg2)\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17172/"
] |
283,468
|
<p>In C# you can use verbatim strings like this:</p>
<pre><code>@"\\server\share\file.txt"
</code></pre>
<p>Is there something similar in JavaScript?</p>
|
[
{
"answer_id": 283642,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 5,
"selected": true,
"text": "public void Alert(string message)\n{\n message = message.Replace(\"\\\\\", \"\\\\\\\\\")\n .Replace(\"\\r\\n\", \"\\n\")\n .Replace(\"\\n\", \"\\\\n\")\n .Replace(\"\\t\", \"\\\\t\")\n .Replace(\"\\\"\", \"\\\\\\\"\");\n\n // and now register my JavaScript with this safe string.\n}\n"
},
{
"answer_id": 284022,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 2,
"selected": false,
"text": "\\n \\\\ \\t \"\\a\".replace(\"\\a\",\"\\\\a\") // WORKS \\a\n\"aa\\a\".replace(\"\\a\", \"\\\\a\") // FAILS \\aaa\n [\"\\a\"] a"
},
{
"answer_id": 284483,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 2,
"selected": false,
"text": "<html>\n<head>\n<script>\nfunction foo() {\n var string = document.getElementById('foo').innerHTML;\n alert(string);\n}\nwindow.onload=foo;\n</script>\n<style>\n#foo{\n display: none;\n}\n</style>\n</head>\n<body>\nCalling foo on page load.\n<div id=\"foo\">\\\\server\\path\\to\\file.txt</div>\n</body>\n</html>\n"
},
{
"answer_id": 35571428,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 4,
"selected": false,
"text": "`so you can\ndo this if you want`\n `\"A\\nB\"`\n \"A\nB\"\n JSON.parse"
},
{
"answer_id": 35681749,
"author": "estani",
"author_id": 1182464,
"author_profile": "https://Stackoverflow.com/users/1182464",
"pm_score": 3,
"selected": false,
"text": "function verbatim(fn){return fn.toString().match(/[^]*\\/\\*\\s*([^]*)\\s*\\*\\/\\}$/)[1]}\n var myText = verbatim(function(){/*This\n is a multiline \\a\\n\\0 verbatim line*/})\n"
},
{
"answer_id": 44212558,
"author": "LitoMore",
"author_id": 7819703,
"author_profile": "https://Stackoverflow.com/users/7819703",
"pm_score": 4,
"selected": false,
"text": "String.raw() String.raw`\\n`\n \\\\n\n String.raw`hello`hello` // It will throw an TypeError\nString.raw`hello\\`hello` // Output is 'hello\\\\`hello'\n `"
},
{
"answer_id": 63055984,
"author": "Numan Bin Tariq",
"author_id": 9097483,
"author_profile": "https://Stackoverflow.com/users/9097483",
"pm_score": 2,
"selected": false,
"text": "String.raw(callSite, ...substitutions)\nor \nString.raw`template string`\n const filePath_SimpleString = 'C:\\\\Development\\\\profile\\\\aboutme.html';\nconst filePath_RawString = String.raw`C:\\Development\\profile\\aboutme.html`;\n \nconsole.log(`The file was uploaded from: ${filePath}`);\nconsole.log(`The file was uploaded from: ${filePath}`);\n \n// expected output will be same: \n//\"The file was uploaded from: C:\\Development\\profile\\aboutme.html\"\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4830/"
] |
283,470
|
<p>i get the following error when trying to run a flex application (which has been working fine!). I was playing around with some different setttings trying to optimize the compiled size. I've put these settings back to the defaults as much as I thought but still getting issues.</p>
<p>I remember getting this error before but cant seem to remember how I fixed it - nor any useful information about how to fix it again! </p>
<p>Anybody know?</p>
<p>VerifyError: Error #1014: Class IAutomationObject could not be found.</p>
<pre><code>at flash.display::MovieClip/nextFrame()
at mx.managers::SystemManager/deferredNextFrame()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:299]
at mx.managers::SystemManager/preloader_initProgressHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:2225]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\preloaders\Preloader.as:398]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
</code></pre>
|
[
{
"answer_id": 283642,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 5,
"selected": true,
"text": "public void Alert(string message)\n{\n message = message.Replace(\"\\\\\", \"\\\\\\\\\")\n .Replace(\"\\r\\n\", \"\\n\")\n .Replace(\"\\n\", \"\\\\n\")\n .Replace(\"\\t\", \"\\\\t\")\n .Replace(\"\\\"\", \"\\\\\\\"\");\n\n // and now register my JavaScript with this safe string.\n}\n"
},
{
"answer_id": 284022,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 2,
"selected": false,
"text": "\\n \\\\ \\t \"\\a\".replace(\"\\a\",\"\\\\a\") // WORKS \\a\n\"aa\\a\".replace(\"\\a\", \"\\\\a\") // FAILS \\aaa\n [\"\\a\"] a"
},
{
"answer_id": 284483,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 2,
"selected": false,
"text": "<html>\n<head>\n<script>\nfunction foo() {\n var string = document.getElementById('foo').innerHTML;\n alert(string);\n}\nwindow.onload=foo;\n</script>\n<style>\n#foo{\n display: none;\n}\n</style>\n</head>\n<body>\nCalling foo on page load.\n<div id=\"foo\">\\\\server\\path\\to\\file.txt</div>\n</body>\n</html>\n"
},
{
"answer_id": 35571428,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 4,
"selected": false,
"text": "`so you can\ndo this if you want`\n `\"A\\nB\"`\n \"A\nB\"\n JSON.parse"
},
{
"answer_id": 35681749,
"author": "estani",
"author_id": 1182464,
"author_profile": "https://Stackoverflow.com/users/1182464",
"pm_score": 3,
"selected": false,
"text": "function verbatim(fn){return fn.toString().match(/[^]*\\/\\*\\s*([^]*)\\s*\\*\\/\\}$/)[1]}\n var myText = verbatim(function(){/*This\n is a multiline \\a\\n\\0 verbatim line*/})\n"
},
{
"answer_id": 44212558,
"author": "LitoMore",
"author_id": 7819703,
"author_profile": "https://Stackoverflow.com/users/7819703",
"pm_score": 4,
"selected": false,
"text": "String.raw() String.raw`\\n`\n \\\\n\n String.raw`hello`hello` // It will throw an TypeError\nString.raw`hello\\`hello` // Output is 'hello\\\\`hello'\n `"
},
{
"answer_id": 63055984,
"author": "Numan Bin Tariq",
"author_id": 9097483,
"author_profile": "https://Stackoverflow.com/users/9097483",
"pm_score": 2,
"selected": false,
"text": "String.raw(callSite, ...substitutions)\nor \nString.raw`template string`\n const filePath_SimpleString = 'C:\\\\Development\\\\profile\\\\aboutme.html';\nconst filePath_RawString = String.raw`C:\\Development\\profile\\aboutme.html`;\n \nconsole.log(`The file was uploaded from: ${filePath}`);\nconsole.log(`The file was uploaded from: ${filePath}`);\n \n// expected output will be same: \n//\"The file was uploaded from: C:\\Development\\profile\\aboutme.html\"\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
283,471
|
<p>I know you can do it file by file.</p>
<p>Is there any way to do this in one step for all files in a project?</p>
|
[
{
"answer_id": 283474,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "Imports System\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module OrganiseUsings\n\n Public Sub RemoveAndSortAll()\n On Error Resume Next\n Dim sol As Solution = DTE.Solution\n\n For i As Integer = 1 To sol.Projects.Count \n Dim proj As Project = sol.Projects.Item(i) \n For j As Integer = 1 To proj.ProjectItems.Count \n RemoveAndSortSome(proj.ProjectItems.Item(j)) \n Next \n Next \n End Sub \n\n Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)\n On Error Resume Next\n If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then \n If projectItem.Name.LastIndexOf(\".cs\") = projectItem.Name.Length - 3 Then\n Dim window As Window = projectItem.Open(Constants.vsViewKindCode)\n\n window.Activate()\n\n projectItem.Document.DTE.ExecuteCommand(\"Edit.RemoveAndSort\")\n\n window.Close(vsSaveChanges.vsSaveChangesYes)\n End If \n End If \n\n For i As Integer = 1 To projectItem.ProjectItems.Count \n RemoveAndSortSome(projectItem.ProjectItems.Item(i)) \n Next\n End Sub \n\nEnd Module\n"
},
{
"answer_id": 10531081,
"author": "mghaoui",
"author_id": 32824,
"author_profile": "https://Stackoverflow.com/users/32824",
"pm_score": 2,
"selected": false,
"text": " Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)\n On Error Resume Next\n If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then\n If projectItem.Name.LastIndexOf(\".cs\") = projectItem.Name.Length - 3 Then\n Dim window As Window = projectItem.Open(Constants.vsViewKindCode)\n\n window.Activate()\n\n projectItem.Document.DTE.ExecuteCommand(\"Edit.RemoveAndSort\")\n\n window.Close(vsSaveChanges.vsSaveChangesYes)\n\n ElseIf projectItem.Name.LastIndexOf(\".vb\") = projectItem.Name.Length - 3 Then\n Dim window As Window = projectItem.Open(Constants.vsViewKindCode)\n\n window.Activate()\n\n projectItem.Document.DTE.ExecuteCommand(\"EditorContextMenus.CodeWindow.OrganizeImports.RemoveandSortImports\")\n\n window.Close(vsSaveChanges.vsSaveChangesYes)\n End If\n End I\n"
},
{
"answer_id": 50632775,
"author": "sotn",
"author_id": 944592,
"author_profile": "https://Stackoverflow.com/users/944592",
"pm_score": 7,
"selected": false,
"text": "Solution Fix all occurrences in"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
283,476
|
<p>I am wondering what is the "best practice" to break long strings in C# source code. Is this string </p>
<pre><code>"string1"+
"string2"+
"string3"
</code></pre>
<p>concatenated during compiling or in run time?</p>
|
[
{
"answer_id": 283491,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "string x = \"string1string2string3\"\nstring y = \"string1\" + \"string2\" + \"string3\"\n StringBuilder StringBuilder StringBuilder"
},
{
"answer_id": 283494,
"author": "Damien",
"author_id": 35454,
"author_profile": "https://Stackoverflow.com/users/35454",
"pm_score": 0,
"selected": false,
"text": "StringBuilder"
},
{
"answer_id": 283505,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 6,
"selected": false,
"text": "string query = @\"SELECT whatever\nFROM tableName\nWHERE column = 1\";\n"
},
{
"answer_id": 283507,
"author": "Sani Singh Huttunen",
"author_id": 26742,
"author_profile": "https://Stackoverflow.com/users/26742",
"pm_score": 1,
"selected": false,
"text": "string a = \"string1\";\nstring b = \"string2\";\nstring c = a + b;\n"
},
{
"answer_id": 53973356,
"author": "Felix K.",
"author_id": 2477619,
"author_profile": "https://Stackoverflow.com/users/2477619",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Text.RegularExpressions;\nusing static System.Text.RegularExpressions.RegexOptions;\n\nnamespace My.Name.Space\n{\n public static class StringHelper\n {\n public static string AsOneLine(this string text, string separator = \" \")\n {\n return new Regex(@\"(?:\\n(?:\\s*))+\").Replace(text, separator).Trim();\n }\n }\n}\n var mySingleLineText = @\"\n If we wish to count lines of code, we should not regard them\n as 'lines produced' but as 'lines spent'.\n\".AsOneLine();\n // foo bar hello world.\nvar mySingleLineText = @\"\n foo bar\n hello world.\n\".AsOneLine();\n \"\" // foobar\nvar mySingleLineText = @\"\n foo\n bar\n\".AsOneLine(\"\");\n + +"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
283,477
|
<p>Suppose I have the following directory layout in a Maven project:</p>
<pre><code>src/
|-- main
| |-- bin
| | |-- run.cmd
| | `-- run.sh
| |-- etc
| | |-- common-spring.xml
| | |-- log4j.xml
| | `-- xml-spring.xml
| `-- java
| `-- com
...
</code></pre>
<p>I would like to build a zip file that, when unzipped, produces something like this:</p>
<pre><code>assembly
|-- bin
| |-- run.cmd
| `-- run.sh
|-- etc
| |-- common-spring.xml
| |-- log4j.xml
| `-- xml-spring.xml
`-- lib
|-- dependency1.jar
|-- dependency2.jar
...
</code></pre>
<p>where `run.xx' are executable shell scripts that will call my main application and <em>put all dependencies on the classpath</em>.</p>
<p>Is this possible with some of the `official' Maven plugins, e.g. maven-assembly-plugin?</p>
|
[
{
"answer_id": 283564,
"author": "jassuncao",
"author_id": 1009,
"author_profile": "https://Stackoverflow.com/users/1009",
"pm_score": 5,
"selected": true,
"text": "...\n<build>\n<plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>appassembler-maven-plugin</artifactId>\n <configuration>\n <programs>\n <program>\n <mainClass>com.acme.MainClass</mainClass>\n <name>app</name>\n </program>\n </programs>\n </configuration>\n </plugin>\n</plugins>\n"
},
{
"answer_id": 287494,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<dependencySets>\n <!-- Copy dependency jar files to 'lib' -->\n <dependencySet>\n <outputDirectory>lib</outputDirectory>\n <includes>\n <include>*:jar:*</include>\n </includes>\n </dependencySet>\n</dependencySets>\n"
},
{
"answer_id": 301222,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<assembly>\n <id>distribution</id>\n\n <!-- specify the output formats -->\n <formats>\n <format>zip</format>\n </formats>\n\n <!-- include all runtime libraries in the /lib folder of the output file -->\n <dependencySets>\n <dependencySet>\n <outputDirectory>/lib</outputDirectory>\n <scope>runtime</scope>\n </dependencySet>\n </dependencySets>\n\n <fileSets>\n <!-- include all *.jar files in the target directory -->\n <fileSet>\n <directory>target</directory>\n <outputDirectory></outputDirectory>\n <includes>\n <include>*.jar</include>\n </includes>\n </fileSet>\n\n <!-- include all files in the /conf directory -->\n <fileSet>\n <outputDirectory></outputDirectory>\n <includes>\n <include>conf/**</include>\n </includes>\n </fileSet>\n </fileSets>\n\n</assembly>\n <plugin>\n <artifactId>maven-assembly-plugin</artifactId>\n\n <configuration>\n <descriptors>\n <descriptor>src/assemble/distribution.xml\n </descriptor>\n </descriptors>\n </configuration>\n\n <!-- append assembly:assembly to the package phase -->\n <executions>\n <execution>\n <phase>package</phase>\n <goals>\n <goal>assembly</goal>\n </goals>\n </execution>\n </executions>\n\n </plugin>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428/"
] |
283,484
|
<p>Is there anything similar to getElementById in actionscript? </p>
<p>I'm trying to make a prototype of a flash page wich gets it's data from a xhtml file. I want to have both an accessible html version (for search engines, textreaders and people without flash) and a flash version (because the customer insists to use flash even though a html-css-ajax solution would do quite nicely). </p>
<p>What I need is a simple way of getting the text or attributes from the html with a certain id, like <code><h1 id="flashdataTitle">This is the title</h1></code> etc. I'm guessing a few ways it might be possible:</p>
<ul>
<li>Somehow use an ExternalInterface.call and do the DOM trickery in JavaScript (wich is probably what I will do, because I'm very familiar with JS and a complete newbie with flash/actionscript, unless you have a better solution)</li>
<li>Load the xhtml with the Actionscript XML class, and manually traverse the XML looking for the correct id attribute (but this is probably very slow)</li>
<li>Use XPath with the XML class in actionscript. (I'd like some hints on how to do this, if this is the reccomended way)</li>
<li>There is actually an Actionscript equivalent to getElementById to use with the XML?</li>
<li>Allthough my employer hope we don't have to do this: I could rewrite the server side code to output the relevant texts and image urls in a flash-friendly format.</li>
</ul>
<p>What is the most effective, easiest to implement, and robust-crossbrowser way of doing this? Any totally different ideas?</p>
<p>Please post any ideas even if you think the question have been answered, I'd like to explore all the different possibilities, and allso what disadvantages the proposed solutions have.</p>
|
[
{
"answer_id": 283552,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": true,
"text": "import mx.xpath.XPathAPI;\n\nvar elementId:String = \"flashdataTitle\";\nvar elementPath:String = \"//h1[@id'\" + elementId + \"']\";\nfound_elements = XPathAPI.selectNodeList(xhtml.firstChild, elementPath);\n\nif (found_elements.length == 1) {\n trace(found_elements[0]);\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26115/"
] |
283,486
|
<p>We are experiencing a strange bug on our website which we think is related to the software installed on user's computers. We have an e-mail link on a lot of pages, which is created using Javascript (so spambots won't get it).</p>
<p>It seems the link is "clicked" automatically on some user's machines. Some users then discard the window by clicking Send on the e-mail window that pops up, resulting in a ton of e-mails to us.</p>
<p>When inspecting the Apache log, nothing weird can be seen in the browser string. Can this be a download accelerator/prefetcher gone haywire? Any other theories as to what this might be?</p>
<p>The link in the HTML is written like this (it is autogenerated by Smarty):</p>
<pre><code><script type="text/javascript" language="javascript">
<!--
{document.write(String.fromCharCode(60,97,32,104,114,101,
102,61,34,109,97,105,108,116,111,58,115,117,112,112,111,114,
116,64,112,114,111,118,101,46,110,111,63,115,117,98,106,101,99,
116,61,82,101,102,101,114,97,110,115,101,110,117,109,109,101,114,
37,50,48,49,53,48,48,34,32,62,83,101,110,100,32,115,112,38,111,115,
108,97,115,104,59,114,115,109,38,97,114,105,110,103,59,108,46,60,47,97,62))}
//-->
</script>
</code></pre>
|
[
{
"answer_id": 1361093,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "mailto:"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606/"
] |
283,489
|
<p>I'm using maven 2.0.9 with Eclipse 3.3.2.</p>
<p>I'm used to launching a fresh build once per day by a <code>mvn clean install</code>.
Then, if I refresh my Eclipse project, it will be "polluted" by files from Maven's <em>target</em> directory.</p>
<p>That's very annoying while performing searches, getting resources by "open resource" and so on.</p>
<p>Is there a way to avoid Eclipse looking in this folder?</p>
|
[
{
"answer_id": 5539274,
"author": "Marx",
"author_id": 691183,
"author_profile": "https://Stackoverflow.com/users/691183",
"pm_score": 5,
"selected": false,
"text": "<plugin>\n <artifactId>maven-clean-plugin</artifactId>\n <configuration>\n <excludeDefaultDirectories>true</excludeDefaultDirectories>\n <filesets>\n <!-- delete directories that will be generated when you \n start the develpment server/client in eclipse \n -->\n <fileset>\n <directory>target</directory>\n <includes>\n <include>**/*</include>\n </includes>\n </fileset>\n </filesets>\n </configuration>\n</plugin>\n"
},
{
"answer_id": 6360001,
"author": "Stephen Hart",
"author_id": 799852,
"author_profile": "https://Stackoverflow.com/users/799852",
"pm_score": 2,
"selected": false,
"text": "/*\n * Menu: Find System Prints > Beanshell\n * Script-Path: /GroovyMonkeyScripts/monkey/UpdateMavenDerived_Beanshell.gm\n * Kudos: Bjorn Freeman-Benson & Ward Cunningham & James E. Ervin\n * License: EPL 1.0\n * LANG: Beanshell\n * DOM: http://groovy-monkey.sourceforge.net/update/plugins/net.sf.groovyMonkey.dom\n */\nout.println(\"Setting target directories to derived status.\");\nvar projects = workspace.getRoot().getProjects();\nfor ( var i = 0; i < projects.length; i++) {\n var project = projects[i];\n if (project.isOpen()) {\n out.println(\"Project: \" + project.getName());\n var members = project.members();\n for ( var j = 0; j < members.length; j++) {\n if (members[j].getName().equals(\"target\")) {\n out.println(\"setting derived status on: \"+ members[j].getFullPath());\n members[j].setDerived(true);\n }\n }\n }\n}\n"
},
{
"answer_id": 7210006,
"author": "Who Mobile",
"author_id": 493789,
"author_profile": "https://Stackoverflow.com/users/493789",
"pm_score": 1,
"selected": false,
"text": "function eclipse-setup() {\n mvn eclipse:clean\n mvn eclipse:eclipse\n #maven target folders\n find . -name .project -exec sed -i.MSORG 's/<\\/projectDescription>/<filteredResources> <filter> <id>1314376338264<\\/id> <name><\\/name> <type>26\n<\\/type> <matcher> <id>org.eclipse.ui.ide.multiFilter<\\/id> <arguments>1.0-name-matches-false-false-target<\\/arguments> <\\/matcher> <\\/filter> <filt\ner> <id>1314387234341<\\/id> <name><\\/name> <type>6<\\/type> <matcher> <id>org.eclipse.ui.ide.multiFilter<\\/id> <arguments>1.0-name-matches-false-fals\ne-*.cache.html<\\/arguments> <\\/matcher> <\\/filter> <\\/filteredResources><\\/projectDescription>/' {} \\;\n\n}\n"
},
{
"answer_id": 16241161,
"author": "Mike R",
"author_id": 2272030,
"author_profile": "https://Stackoverflow.com/users/2272030",
"pm_score": 4,
"selected": false,
"text": "Project Explorer Customize View Filters [*] Maven Build Folder"
},
{
"answer_id": 29270525,
"author": "kapex",
"author_id": 897024,
"author_profile": "https://Stackoverflow.com/users/897024",
"pm_score": 2,
"selected": false,
"text": "Filters... Name filter patterns target target Custom View... Maven build folder"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] |
283,492
|
<p>I'm tring to build a library for simplifing late binding calls in C#, and I'm getting trouble tring with reference parameteres. I have the following method to add a parameter used in a method call</p>
<pre><code> public IInvoker AddParameter(ref object value)
{
//List<object> _parameters = new List<object>();
_parameters.Add(value);
//List<bool> _isRef = new List<bool>();
_isRef.Add(true);
return this;
}
</code></pre>
<p>And that doesn't work with value types, because they get boxed as an object, thus they are not modified. E.g:</p>
<pre><code>int param1 = 2;
object paramObj = param1;
//MulFiveRef method multiplies the integer passed as a reference parameter by 5:
//void MulFiveRef(ref int value) { value *= 5; }
fi.Method("MulFiveRef").AddParameter(ref paramObj);
</code></pre>
<p>That doesn't work. The late binding call is successful, and the inner List which holds the parameteres (_parameters ) does get modified, but not the value outside the call.</p>
<p>Does anyone knows a simple way to overcome this limitation?
The AddParameter signature cannot be modified, as with late binding calls, you cannot know in advance the Type of the parameters (and either way you insert all the parameters for a call inside an object array prior to making the call)</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 283499,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "value ref ref public class Test\n{\n static void Main()\n {\n int i;\n Foo(ref i); // Won't compile - error CS1502/1503\n }\n\n static void Foo(ref object x)\n {\n }\n}\n AddParameter ref int"
},
{
"answer_id": 283500,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "object ref int i = 3;\n //...\n object obj = i;\n Foo(ref obj);\n i = (int)obj;\n ref object dynamic"
},
{
"answer_id": 283769,
"author": "Ricardo Amores",
"author_id": 10136,
"author_profile": "https://Stackoverflow.com/users/10136",
"pm_score": 0,
"selected": false,
"text": " //This will be created with a factory\n IOperationInvoker invoker = new OperationInvoker(Activator.CreateInstance<MyLateBindingTestType>());\n\n int param1 = 2;\n object paramObj = param1;\n\n invoker.AddParameter(ref paramObj).Invoke(\"MulFiveRef\");\n\n param1 = (int)invoker.Parameters[0];\n IOperationInvoker invoker = new OperationInvoker(Activator.CreateInstance<MyLateBindingTestType>());\n int refValue = 10;\n object[] args = Args.Build(refValue);\n\n invoker.Call(\"MulFiveRef\", Args.ByRefIndexs(0), args);\n\n refValue = (int)args[0];\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10136/"
] |
283,497
|
<p>Should I use the <code>change</code> or <code>textInput</code> event to capture user input on a TextInput control? Why?</p>
|
[
{
"answer_id": 283767,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 7,
"selected": true,
"text": "textInput change change flash.events.TextEvent.TEXT_INPUT flash.events.Event.CHANGE valueCommit"
},
{
"answer_id": 309663,
"author": "Ross Henderson",
"author_id": 37446,
"author_profile": "https://Stackoverflow.com/users/37446",
"pm_score": 2,
"selected": false,
"text": "this.addEventListener(Event.CHANGE, textFieldChangeListener); \nthis.addEventListener(TextEvent.TEXT_INPUT,textFieldInputListener);\n"
},
{
"answer_id": 8731293,
"author": "Daniel Z",
"author_id": 1130485,
"author_profile": "https://Stackoverflow.com/users/1130485",
"pm_score": 0,
"selected": false,
"text": "CHANGE TEXT_INPUT KEY_DOWN"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36817/"
] |
283,513
|
<p>We just shifted from VB to C# and I am having some troubles..!</p>
<p>Why can't I create a private static const void?? </p>
<p>why is it not working?</p>
<pre><code> private static const void MyVoid(void void)
{
try
{
this.void void = new void(void + void);
return this.void;
}
catch (void)
{
Response.Write(void);
}
}
</code></pre>
|
[
{
"answer_id": 283517,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "void int bool"
},
{
"answer_id": 283526,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "const void"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36864/"
] |
283,523
|
<p>I have a C# application where i want to implement a logic for a programm which will open the word document and go to a certain place in the page and create a Table and put values in that. Can any one tell me how to implement this. I am using Visual studio 2005 </p>
|
[
{
"answer_id": 10769658,
"author": "Gary Kindel",
"author_id": 44597,
"author_profile": "https://Stackoverflow.com/users/44597",
"pm_score": 3,
"selected": false,
"text": "using word = Microsoft.Office.Interop.Word; \npublic static void ExportToWord(DataGridView dgv)\n {\n SendMessage(\"Opening Word\");\n\n word.ApplicationClass word = null;\n\n\n\n word.Document doc = null;\n object oMissing = System.Reflection.Missing.Value;\n object oEndOfDoc = \"\\\\endofdoc\"; /* \\endofdoc is a predefined bookmark */ \n try\n {\n word = new word.ApplicationClass();\n word.Visible = true;\n doc = word.Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing);\n }\n catch (Exception ex)\n {\n ErrorLog(ex);\n }\n finally\n {\n }\n if (word != null && doc != null)\n {\n word.Table newTable;\n word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;\n newTable = doc.Tables.Add(wrdRng, 1, dgv.Columns.Count-1, ref oMissing, ref oMissing);\n newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;\n newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;\n newTable.AllowAutoFit = true;\n\n foreach (DataGridViewCell cell in dgv.Rows[0].Cells)\n {\n newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = dgv.Columns[cell.ColumnIndex].Name;\n\n }\n newTable.Rows.Add();\n\n foreach (DataGridViewRow row in dgv.Rows)\n {\n foreach (DataGridViewCell cell in row.Cells)\n {\n newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = cell.Value.ToString(); \n }\n newTable.Rows.Add();\n } \n }\n\n }\n"
},
{
"answer_id": 29876521,
"author": "nassimlouchani",
"author_id": 3261559,
"author_profile": "https://Stackoverflow.com/users/3261559",
"pm_score": 0,
"selected": false,
"text": " using Word = Microsoft.Office.Interop.Word;\n\n public void Export_Data_To_Word(DataGridView DGV, string filename)\n {\n if (DGV.Rows.Count != 0)\n {\n int RowCount = DGV.Rows.Count;\n int ColumnCount = DGV.Columns.Count;\n Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];\n\n //add rows\n int r = 0;\n for (int c = 0; c <= ColumnCount - 1; c++)\n {\n for (r = 0; r <= RowCount - 1; r++)\n {\n DataArray[r, c] = DGV.Rows[r].Cells[c].Value;\n } //end row loop\n } //end column loop\n\n Word.Document oDoc = new Word.Document();\n oDoc.Application.Visible = true;\n\n //page orintation\n oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;\n\n\n dynamic oRange = oDoc.Content.Application.Selection.Range;\n string oTemp = \"\";\n for (r = 0; r <= RowCount - 1; r++)\n {\n for (int c = 0; c <= ColumnCount - 1; c++)\n {\n oTemp = oTemp + DataArray[r, c] + \"\\t\";\n\n }\n }\n\n //table format\n oRange.Text = oTemp;\n\n object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;\n object ApplyBorders = true;\n object AutoFit = true;\n object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;\n\n oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,\n Type.Missing, Type.Missing, ref ApplyBorders,\n Type.Missing, Type.Missing, Type.Missing,\n Type.Missing, Type.Missing, Type.Missing,\n Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);\n\n oRange.Select();\n\n oDoc.Application.Selection.Tables[1].Select();\n oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;\n oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;\n oDoc.Application.Selection.Tables[1].Rows[1].Select();\n oDoc.Application.Selection.InsertRowsAbove(1);\n oDoc.Application.Selection.Tables[1].Rows[1].Select();\n\n //header row style\n oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;\n oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = \"Tahoma\";\n oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;\n\n //add header row manually\n for (int c = 0; c <= ColumnCount - 1; c++)\n {\n oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;\n }\n\n //table style \n oDoc.Application.Selection.Tables[1].set_Style(\"Grid Table 4 - Accent 5\");\n oDoc.Application.Selection.Tables[1].Rows[1].Select();\n oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;\n\n //header text\n foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)\n {\n Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;\n headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);\n headerRange.Text = \"your header text\";\n headerRange.Font.Size = 16;\n headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;\n }\n\n //save the file\n oDoc.SaveAs2(filename);\n\n //NASSIM LOUCHANI\n } \n }\n\n\n\n\n private void button_Click(object sender, EventArgs e)\n {\n SaveFileDialog sfd = new SaveFileDialog();\n\n sfd.Filter = \"Word Documents (*.docx)|*.docx\";\n\n sfd.FileName = \"export.docx\";\n\n if (sfd.ShowDialog() == DialogResult.OK)\n {\n\n Export_Data_To_Word(dataGridView1, sfd.FileName); \n }\n }\n"
},
{
"answer_id": 59755161,
"author": "Osiel López",
"author_id": 12718905,
"author_profile": "https://Stackoverflow.com/users/12718905",
"pm_score": 0,
"selected": false,
"text": "public void tableFromDatabase(Document doc, Application word, string risk, string bookmarkName, TableTemplate table) {\n Table newTable;//Create a new table\n Range wrdRng = doc.Bookmarks.get_Item(bookmarkName).Range;//Get a bookmark Range\n doc.Bookmarks[bookmarkName].Select();\n newTable = word.Selection.Tables.Add(wrdRng,1,1);//Add new table to selected bookmark by default set 1 row, 1 column (need set interval 1-63)\n newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;\n newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;\n int a=0, b=0;//Set integer values for iterate in model arrays\n //Iterate model rows\n for (int i = 1; i <= table.Rows.Count; i++)//Set in 1 the value because in word tables the begin is (1,1)\n {\n //Only add rows if is after first row\n if (i > 1)\n {\n newTable.Rows.Add();\n }\n //Iterate model columns from rows\n for (int j = 1; j <= table.Rows[a].Columns.Count; j++)\n {\n //Only Add rows if is after first\n if (j == 1 && i == 1)\n {\n newTable.Cell(i, j).Range.Font.Name = table.Rows[a].Columns[b].cellFontName;\n newTable.Cell(i, j).Range.Font.Size = table.Rows[a].Columns[b].cellFontSize;\n newTable.Cell(i, j).Width = float.Parse(table.Rows[a].Columns[b].cellWidth);\n }\n else\n {\n //Add Cells to rows only if columns of the model is largen than table, this is for not exceed the interval\n if (newTable.Rows[i].Cells.Count < table.Rows[a].Columns.Count)\n {\n newTable.Rows[i].Cells.Add();\n }\n //Set the values to new table\n //The width must be float type\n newTable.Cell(i, j).Range.Font.Name = table.Rows[a].Columns[b].cellFontName;\n newTable.Cell(i, j).Range.Font.Size = table.Rows[a].Columns[b].cellFontSize;\n newTable.Cell(i, j).Width = float.Parse(table.Rows[a].Columns[b].cellWidth);\n }\n b++;\n //Set 0 to reset cycle\n if (b == table.Rows[a].Columns.Count)\n {\n b = 0;\n }\n }\n a++;\n //Set 0 to reset cycle\n if (a == table.Rows.Count)\n {\n a = 0;\n }\n }\n newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;\n newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;\n newTable.AllowAutoFit = true;\n //Set gray color to borders\n newTable.Borders.InsideColor = (Microsoft.Office.Interop.Word.WdColor)12964311;\n newTable.Borders.OutsideColor = (Microsoft.Office.Interop.Word.WdColor)12964311;\n\n }\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,525
|
<p>This line:</p>
<pre><code>strcat(query,*it);
</code></pre>
<p>(where <code>*it</code> is an iterator to a string)</p>
<p>Keeps giving me this error:</p>
<blockquote>
<p>no matching function for call to ``strcat(char[200], const std::basic_string, std::allocator >&)`' </p>
</blockquote>
<p>I guess it's because <code>strcat</code> takes in a <code>char*</code> while <code>*it</code> is a string.
How do I convert it from a string to a <code>char*</code> to make it work with <code>strcat()</code> ?</p>
<p>I've tried <code>strcat(query,(*it).c_str())</code> but that just gives me a runtime error.</p>
<p>Edit: sorry, it should be converted to a <code>const char*</code></p>
|
[
{
"answer_id": 283531,
"author": "tragomaskhalos",
"author_id": 31140,
"author_profile": "https://Stackoverflow.com/users/31140",
"pm_score": 3,
"selected": false,
"text": "strcat(query,(*it).c_str()) query"
},
{
"answer_id": 283532,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "c_str() strcat()"
},
{
"answer_id": 283538,
"author": "Stefan Rådström",
"author_id": 19981,
"author_profile": "https://Stackoverflow.com/users/19981",
"pm_score": 0,
"selected": false,
"text": "for (...; it != str.end(); ++it)\n...\n if (!it->empty())\n {\n strcat(query, it->c_str());\n }\n"
},
{
"answer_id": 283699,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "char query[200] = {0}; // Make sure this array initialized before\n // you start concatenating strings onto it.\n\nfor (it = vec.begin();it != vec.end();++it)\n{\n if ((strlen(query) + it->length() + 1) >= 200)\n {\n logError(\"Buffer oveflow detected.\";\n break;\n }\n strcat(query, it->c_str());\n}\n"
},
{
"answer_id": 284046,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 1,
"selected": false,
"text": "strcat strncat std::string"
},
{
"answer_id": 285673,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "query query (*it).c_str() it query it"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
283,537
|
<p>Given a method signature:</p>
<pre><code>public bool AreTheSame<T>(Expression<Func<T, object>> exp1, Expression<Func<T, object>> exp2)
</code></pre>
<p>What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple MemberExpressions, eg c => c.ID.</p>
<p>An example call might be:</p>
<pre><code>AreTheSame<User>(u1 => u1.ID, u2 => u2.ID); --> would return true
</code></pre>
|
[
{
"answer_id": 283546,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "using System;\nusing System.Linq.Expressions;\nclass Test {\n public string Foo { get; set; }\n public string Bar { get; set; }\n static void Main()\n {\n bool test1 = FuncTest<Test>.FuncEqual(x => x.Bar, y => y.Bar),\n test2 = FuncTest<Test>.FuncEqual(x => x.Foo, y => y.Bar);\n }\n\n}\n// this only exists to make it easier to call, i.e. so that I can use FuncTest<T> with\n// generic-type-inference; if you use the doubly-generic method, you need to specify\n// both arguments, which is a pain...\nstatic class FuncTest<TSource>\n{\n public static bool FuncEqual<TValue>(\n Expression<Func<TSource, TValue>> x,\n Expression<Func<TSource, TValue>> y)\n {\n return FuncTest.FuncEqual<TSource, TValue>(x, y);\n }\n}\nstatic class FuncTest {\n public static bool FuncEqual<TSource, TValue>(\n Expression<Func<TSource,TValue>> x,\n Expression<Func<TSource,TValue>> y)\n {\n return ExpressionEqual(x, y);\n }\n private static bool ExpressionEqual(Expression x, Expression y)\n {\n // deal with the simple cases first...\n if (ReferenceEquals(x, y)) return true;\n if (x == null || y == null) return false;\n if ( x.NodeType != y.NodeType\n || x.Type != y.Type ) return false;\n\n switch (x.NodeType)\n {\n case ExpressionType.Lambda:\n return ExpressionEqual(((LambdaExpression)x).Body, ((LambdaExpression)y).Body);\n case ExpressionType.MemberAccess:\n MemberExpression mex = (MemberExpression)x, mey = (MemberExpression)y;\n return mex.Member == mey.Member; // should really test down-stream expression\n default:\n throw new NotImplementedException(x.NodeType.ToString());\n }\n }\n}\n"
},
{
"answer_id": 24528357,
"author": "neleus",
"author_id": 2528649,
"author_profile": "https://Stackoverflow.com/users/2528649",
"pm_score": 6,
"selected": false,
"text": "public static class LambdaCompare\n{\n public static bool Eq<TSource, TValue>(\n Expression<Func<TSource, TValue>> x,\n Expression<Func<TSource, TValue>> y)\n {\n return ExpressionsEqual(x, y, null, null);\n }\n\n public static bool Eq<TSource1, TSource2, TValue>(\n Expression<Func<TSource1, TSource2, TValue>> x,\n Expression<Func<TSource1, TSource2, TValue>> y)\n {\n return ExpressionsEqual(x, y, null, null);\n }\n\n public static Expression<Func<Expression<Func<TSource, TValue>>, bool>> Eq<TSource, TValue>(Expression<Func<TSource, TValue>> y)\n {\n return x => ExpressionsEqual(x, y, null, null);\n }\n\n private static bool ExpressionsEqual(Expression x, Expression y, LambdaExpression rootX, LambdaExpression rootY)\n {\n if (ReferenceEquals(x, y)) return true;\n if (x == null || y == null) return false;\n\n var valueX = TryCalculateConstant(x);\n var valueY = TryCalculateConstant(y);\n\n if (valueX.IsDefined && valueY.IsDefined)\n return ValuesEqual(valueX.Value, valueY.Value);\n\n if (x.NodeType != y.NodeType\n || x.Type != y.Type)\n {\n if (IsAnonymousType(x.Type) && IsAnonymousType(y.Type))\n throw new NotImplementedException(\"Comparison of Anonymous Types is not supported\");\n return false;\n }\n\n if (x is LambdaExpression)\n {\n var lx = (LambdaExpression)x;\n var ly = (LambdaExpression)y;\n var paramsX = lx.Parameters;\n var paramsY = ly.Parameters;\n return CollectionsEqual(paramsX, paramsY, lx, ly) && ExpressionsEqual(lx.Body, ly.Body, lx, ly);\n }\n if (x is MemberExpression)\n {\n var mex = (MemberExpression)x;\n var mey = (MemberExpression)y;\n return Equals(mex.Member, mey.Member) && ExpressionsEqual(mex.Expression, mey.Expression, rootX, rootY);\n }\n if (x is BinaryExpression)\n {\n var bx = (BinaryExpression)x;\n var by = (BinaryExpression)y;\n return bx.Method == @by.Method && ExpressionsEqual(bx.Left, @by.Left, rootX, rootY) &&\n ExpressionsEqual(bx.Right, @by.Right, rootX, rootY);\n }\n if (x is UnaryExpression)\n {\n var ux = (UnaryExpression)x;\n var uy = (UnaryExpression)y;\n return ux.Method == uy.Method && ExpressionsEqual(ux.Operand, uy.Operand, rootX, rootY);\n }\n if (x is ParameterExpression)\n {\n var px = (ParameterExpression)x;\n var py = (ParameterExpression)y;\n return rootX.Parameters.IndexOf(px) == rootY.Parameters.IndexOf(py);\n }\n if (x is MethodCallExpression)\n {\n var cx = (MethodCallExpression)x;\n var cy = (MethodCallExpression)y;\n return cx.Method == cy.Method\n && ExpressionsEqual(cx.Object, cy.Object, rootX, rootY)\n && CollectionsEqual(cx.Arguments, cy.Arguments, rootX, rootY);\n }\n if (x is MemberInitExpression)\n {\n var mix = (MemberInitExpression)x;\n var miy = (MemberInitExpression)y;\n return ExpressionsEqual(mix.NewExpression, miy.NewExpression, rootX, rootY)\n && MemberInitsEqual(mix.Bindings, miy.Bindings, rootX, rootY);\n }\n if (x is NewArrayExpression)\n {\n var nx = (NewArrayExpression)x;\n var ny = (NewArrayExpression)y;\n return CollectionsEqual(nx.Expressions, ny.Expressions, rootX, rootY);\n }\n if (x is NewExpression)\n {\n var nx = (NewExpression)x;\n var ny = (NewExpression)y;\n return\n Equals(nx.Constructor, ny.Constructor)\n && CollectionsEqual(nx.Arguments, ny.Arguments, rootX, rootY)\n && (nx.Members == null && ny.Members == null\n || nx.Members != null && ny.Members != null && CollectionsEqual(nx.Members, ny.Members));\n }\n if (x is ConditionalExpression)\n {\n var cx = (ConditionalExpression)x;\n var cy = (ConditionalExpression)y;\n return\n ExpressionsEqual(cx.Test, cy.Test, rootX, rootY)\n && ExpressionsEqual(cx.IfFalse, cy.IfFalse, rootX, rootY)\n && ExpressionsEqual(cx.IfTrue, cy.IfTrue, rootX, rootY);\n }\n\n throw new NotImplementedException(x.ToString());\n }\n\n private static Boolean IsAnonymousType(Type type)\n {\n Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any();\n Boolean nameContainsAnonymousType = type.FullName.Contains(\"AnonymousType\");\n Boolean isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;\n\n return isAnonymousType;\n }\n\n private static bool MemberInitsEqual(ICollection<MemberBinding> bx, ICollection<MemberBinding> by, LambdaExpression rootX, LambdaExpression rootY)\n {\n if (bx.Count != by.Count)\n {\n return false;\n }\n\n if (bx.Concat(by).Any(b => b.BindingType != MemberBindingType.Assignment))\n throw new NotImplementedException(\"Only MemberBindingType.Assignment is supported\");\n\n return\n bx.Cast<MemberAssignment>().OrderBy(b => b.Member.Name).Select((b, i) => new { Expr = b.Expression, b.Member, Index = i })\n .Join(\n by.Cast<MemberAssignment>().OrderBy(b => b.Member.Name).Select((b, i) => new { Expr = b.Expression, b.Member, Index = i }),\n o => o.Index, o => o.Index, (xe, ye) => new { XExpr = xe.Expr, XMember = xe.Member, YExpr = ye.Expr, YMember = ye.Member })\n .All(o => Equals(o.XMember, o.YMember) && ExpressionsEqual(o.XExpr, o.YExpr, rootX, rootY));\n }\n\n private static bool ValuesEqual(object x, object y)\n {\n if (ReferenceEquals(x, y))\n return true;\n if (x is ICollection && y is ICollection)\n return CollectionsEqual((ICollection)x, (ICollection)y);\n\n return Equals(x, y);\n }\n\n private static ConstantValue TryCalculateConstant(Expression e)\n {\n if (e is ConstantExpression)\n return new ConstantValue(true, ((ConstantExpression)e).Value);\n if (e is MemberExpression)\n {\n var me = (MemberExpression)e;\n var parentValue = TryCalculateConstant(me.Expression);\n if (parentValue.IsDefined)\n {\n var result =\n me.Member is FieldInfo\n ? ((FieldInfo)me.Member).GetValue(parentValue.Value)\n : ((PropertyInfo)me.Member).GetValue(parentValue.Value);\n return new ConstantValue(true, result);\n }\n }\n if (e is NewArrayExpression)\n {\n var ae = ((NewArrayExpression)e);\n var result = ae.Expressions.Select(TryCalculateConstant);\n if (result.All(i => i.IsDefined))\n return new ConstantValue(true, result.Select(i => i.Value).ToArray());\n }\n if (e is ConditionalExpression)\n {\n var ce = (ConditionalExpression)e;\n var evaluatedTest = TryCalculateConstant(ce.Test);\n if (evaluatedTest.IsDefined)\n {\n return TryCalculateConstant(Equals(evaluatedTest.Value, true) ? ce.IfTrue : ce.IfFalse);\n }\n }\n\n return default(ConstantValue);\n }\n\n private static bool CollectionsEqual(IEnumerable<Expression> x, IEnumerable<Expression> y, LambdaExpression rootX, LambdaExpression rootY)\n {\n return x.Count() == y.Count()\n && x.Select((e, i) => new { Expr = e, Index = i })\n .Join(y.Select((e, i) => new { Expr = e, Index = i }),\n o => o.Index, o => o.Index, (xe, ye) => new { X = xe.Expr, Y = ye.Expr })\n .All(o => ExpressionsEqual(o.X, o.Y, rootX, rootY));\n }\n\n private static bool CollectionsEqual(ICollection x, ICollection y)\n {\n return x.Count == y.Count\n && x.Cast<object>().Select((e, i) => new { Expr = e, Index = i })\n .Join(y.Cast<object>().Select((e, i) => new { Expr = e, Index = i }),\n o => o.Index, o => o.Index, (xe, ye) => new { X = xe.Expr, Y = ye.Expr })\n .All(o => Equals(o.X, o.Y));\n }\n\n private struct ConstantValue\n {\n public ConstantValue(bool isDefined, object value)\n : this()\n {\n IsDefined = isDefined;\n Value = value;\n }\n\n public bool IsDefined { get; private set; }\n\n public object Value { get; private set; }\n }\n}\n [TestClass]\npublic class Tests\n{\n [TestMethod]\n public void BasicConst()\n {\n var f1 = GetBasicExpr1();\n var f2 = GetBasicExpr2();\n Assert.IsTrue(LambdaCompare.Eq(f1, f2));\n }\n\n [TestMethod]\n public void PropAndMethodCall()\n {\n var f1 = GetPropAndMethodExpr1();\n var f2 = GetPropAndMethodExpr2();\n Assert.IsTrue(LambdaCompare.Eq(f1, f2));\n }\n\n [TestMethod]\n public void MemberInitWithConditional()\n {\n var f1 = GetMemberInitExpr1();\n var f2 = GetMemberInitExpr2();\n Assert.IsTrue(LambdaCompare.Eq(f1, f2));\n }\n\n [TestMethod]\n public void AnonymousType()\n {\n var f1 = GetAnonymousExpr1();\n var f2 = GetAnonymousExpr2();\n Assert.Inconclusive(\"Anonymous Types are not supported\");\n }\n\n private static Expression<Func<int, string, string>> GetBasicExpr2()\n {\n var const2 = \"some const value\";\n var const3 = \"{0}{1}{2}{3}\";\n return (i, s) =>\n string.Format(const3, (i + 25).ToString(CultureInfo.InvariantCulture), i + s, const2.ToUpper(), 25);\n }\n\n private static Expression<Func<int, string, string>> GetBasicExpr1()\n {\n var const1 = 25;\n return (first, second) =>\n string.Format(\"{0}{1}{2}{3}\", (first + const1).ToString(CultureInfo.InvariantCulture), first + second,\n \"some const value\".ToUpper(), const1);\n }\n\n private static Expression<Func<Uri, bool>> GetPropAndMethodExpr2()\n {\n return u => Uri.IsWellFormedUriString(u.ToString(), UriKind.Absolute);\n }\n\n private static Expression<Func<Uri, bool>> GetPropAndMethodExpr1()\n {\n return arg1 => Uri.IsWellFormedUriString(arg1.ToString(), UriKind.Absolute);\n }\n\n private static Expression<Func<Uri, UriBuilder>> GetMemberInitExpr2()\n {\n var isSecure = true;\n return u => new UriBuilder(u) { Host = string.IsNullOrEmpty(u.Host) ? \"abc\" : \"def\" , Port = isSecure ? 443 : 80 };\n }\n\n private static Expression<Func<Uri, UriBuilder>> GetMemberInitExpr1()\n {\n var port = 443;\n return x => new UriBuilder(x) { Port = port, Host = string.IsNullOrEmpty(x.Host) ? \"abc\" : \"def\" };\n }\n\n private static Expression<Func<Uri, object>> GetAnonymousExpr2()\n {\n return u => new { u.Host , Port = 443, Addr = u.AbsolutePath };\n }\n\n private static Expression<Func<Uri, object>> GetAnonymousExpr1()\n {\n return x => new { Port = 443, x.Host, Addr = x.AbsolutePath };\n }\n}\n"
},
{
"answer_id": 30875144,
"author": "jnm2",
"author_id": 521757,
"author_profile": "https://Stackoverflow.com/users/521757",
"pm_score": 2,
"selected": false,
"text": "IEqualityComparer<Expression> Try Switch Block Goto Label Loop DebugInfo ConstantExpression"
},
{
"answer_id": 61316588,
"author": "Sebastian Xawery Wiśniowiecki",
"author_id": 3099317,
"author_profile": "https://Stackoverflow.com/users/3099317",
"pm_score": 0,
"selected": false,
"text": "Lambdas IEnumerable class LambdaReadyColumn<int> : HashTable<int> \n class LambdaReadyColumn<int> : IEnumabrable<int> \n class LambdaReadyColumn<LambdaReadyColumnItem<T, int>> : IEnumabrable<int> \n//with example constructor like: \npublic LambdaReadyColumn<LambdaReadyColumnItem<T, int>>(Hash, LambdaReadyColumnItem, LambdaReadyColumnItem, T, int); \n Select(T)"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32855/"
] |
283,551
|
<p>I am struggling with a creating a query. It is related to a large and complicated database but for the sake of this post I have boiled the problem down to something simpler.</p>
<p>I have three tables X, Y, Z defined as</p>
<pre><code>CREATE TABLE [dbo].[X](
[ID] [bigint] NOT NULL
)
CREATE TABLE [dbo].[Y](
[ID] [nchar](10) NOT NULL
)
CREATE TABLE [dbo].[Z](
[IDX] [bigint] NOT NULL,
[IDY] [nchar](10) NOT NULL
)
</code></pre>
<p>They contain the following data</p>
<pre><code>Table X Table Y Table Z
ID ID IDX IDY
-- -- --- ---
1 A 1 A
2 B 1 B
3 C 1 A
</code></pre>
<p>I want to create a query that produces the following result</p>
<pre><code>Count IDX IDY
===== === ===
2 1 A
1 1 B
0 1 C
0 2 A
0 2 B
0 2 C
0 3 A
0 3 B
0 3 C
</code></pre>
<p>My initial thought was</p>
<pre><code>SELECT COUNT(*), X.ID, Y.ID
FROM
X
CROSS JOIN Y
FULL OUTER JOIN Z ON X.ID = Z.IDX AND Y.ID = Z.IDY
GROUP BY X.ID, Y.ID
</code></pre>
<p>but this turns out to be on the wrong road.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 283586,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "SELECT\n COUNT(z.idx) count,\n x.id idx,\n y.id idy\nFROM\n (x CROSS JOIN y)\n LEFT JOIN z ON z.idx = x.id AND z.idy = y.id\nGROUP BY\n x.id,\n y.id\nORDER BY\n COUNT(z.idx) DESC,\n x.id,\n y.id\n"
},
{
"answer_id": 283587,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "SELECT COUNT(*) AS CNT, IDX, IDY\nFROM Z\nGROUP BY IDX, IDY\nUNION\nSELECT 0, X.ID, Y.ID\nFROM X, Y\nWHERE NOT EXISTS (\n SELECT * FROM Z WHERE Z.IDX = X.ID AND Z.IDY = Y.ID\n)\nORDER BY CNT DESC\n"
},
{
"answer_id": 283604,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": true,
"text": "SELECT\n (SELECT COUNT(*) FROM Z WHERE IDX = X.ID AND IDY = Y.ID),\n X.ID,\n Y.ID\nFROM\n X,Y\n"
},
{
"answer_id": 283641,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 0,
"selected": false,
"text": "SELECT (SELECT(COUNT(*) FROM Z) AS COUNT, X.ID AS IDX, y.ID AS IDY\nFROM X CROSS JOIN Y \nORDER BY 1 DESC, 2, 3\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,556
|
<p>I am trying to find the crc that works with the following results. The byte string consists of 2 bytes (ie. 0xCE1E) and the crc is an single byte (ie. 0x03)</p>
<pre>
byte crc
CE1E 03
CE20 45
CE22 6F
0000 C0
0001 D4
FFFF 95
</pre>
<p>Can anyone help?</p>
|
[
{
"answer_id": 848161,
"author": "Eyal",
"author_id": 4454,
"author_profile": "https://Stackoverflow.com/users/4454",
"pm_score": 2,
"selected": false,
"text": "CE1E % p = 03\nCE20 % p = 45\nCE22 % p = 6F\n0000 % p = C0\n0001 % p = D4\nFFFF % p = 95\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,561
|
<p>Inspired by <a href="https://stackoverflow.com/questions/277106/looking-for-some-interesting-c-programming-problems">this question</a>, I wanted to try my hand at the latest <a href="http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/Challenges/November2008.html" rel="nofollow noreferrer">ponder this challenge</a>, using F#</p>
<p>My approach is probably completely off course, but in the course of solving this problem, I'm trying to get a list of all the permutations of the digits 0-9.</p>
<p>I'm looking at solving it using a n-ary tree like so:</p>
<pre><code>type Node =
| Branch of (int * Node list)
| Leaf of int
</code></pre>
<p>I'm quite pleased with myself, because I've managed to work out how to generate the tree that I want. </p>
<p>My problem now is that I can't work out how to traverse this tree and extract the 'path' to each leaf as an int. Thing thing that is confusing me is that I need to match on individual Nodes, but my 'outer' function needs to take a Node list.</p>
<p>My current attempt almost does the right thing, except that it returns me the sum of all the paths...</p>
<pre><code>let test = Branch(3, [Branch(2, [Leaf(1)]);Branch(1, [Leaf(2)])])
let rec visitor lst acc =
let inner n =
match n with
| Leaf(h) -> acc * 10 + h
| Branch(h, t) -> visitor t (acc * 10 + h)
List.map inner lst |> List.sum
visitor [test] 0 //-> gives 633 (which is 321 + 312)
</code></pre>
<p>And I'm not even sure that this is tail-recursive.</p>
<p>(You're quite welcome to propose another solution for finding permutations, but I'm still interested in the solution to this particular problem)</p>
<p>EDIT: I've posted a generic permutations algorithm in F# <a href="https://stackoverflow.com/questions/286427/calculating-permutations-in-f">here</a>.</p>
|
[
{
"answer_id": 283638,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 4,
"selected": true,
"text": "let rec visitor lst tree = \n match tree with\n | Branch(n, sub) -> List.collect (visitor (n::lst)) sub\n | Leaf(n) -> [List.rev (n::lst)]\n\n// For example...\n> let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);;\n> visitor [] tr;;\nval it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]]\n let rec visitor2 lst tree = \n match tree with\n | Branch(n, sub) -> List.collect (visitor2 (lst * 10 + n)) sub\n | Leaf(n) -> [lst * 10 + n]\n\n// For example... \n> visitor2 0 tr;;\nval it : int list = [13; 124; 125] \n"
},
{
"answer_id": 283736,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 2,
"selected": false,
"text": "let rec visitor2 lst tree =\n match tree with\n | Branch(n, sub) -> Seq.map_concat (visitor2 (lst * 10 + n)) sub\n | Leaf(n) ->\n seq { do printfn \"--yielding: %d\" (lst * 10 + n)\n yield lst * 10 + n };;\n > visitor2 0 tr |> Seq.take 2;;\n--yielding: 13\n--yielding: 124\nval it : seq<int> = seq [13; 124]\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
283,575
|
<p>I'm using the ReportViewer control to display a Report within a WebForm, i've also implemented the "Export to Excel" feature, by calling the Render method of the Server Report</p>
<p>eg</p>
<pre><code>ReportViewerControl.ServerReport.Render("Excel",etc,etc,etc);
</code></pre>
<p>My problem is that the exported report contains Hyperlinks that link to other reports, I wish these to appear in the webform but not appear hence be disabled in the Exported Spreadsheet (generated by the Code above).</p>
<p>Does anyone have a way of achieving this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 283638,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 4,
"selected": true,
"text": "let rec visitor lst tree = \n match tree with\n | Branch(n, sub) -> List.collect (visitor (n::lst)) sub\n | Leaf(n) -> [List.rev (n::lst)]\n\n// For example...\n> let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);;\n> visitor [] tr;;\nval it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]]\n let rec visitor2 lst tree = \n match tree with\n | Branch(n, sub) -> List.collect (visitor2 (lst * 10 + n)) sub\n | Leaf(n) -> [lst * 10 + n]\n\n// For example... \n> visitor2 0 tr;;\nval it : int list = [13; 124; 125] \n"
},
{
"answer_id": 283736,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 2,
"selected": false,
"text": "let rec visitor2 lst tree =\n match tree with\n | Branch(n, sub) -> Seq.map_concat (visitor2 (lst * 10 + n)) sub\n | Leaf(n) ->\n seq { do printfn \"--yielding: %d\" (lst * 10 + n)\n yield lst * 10 + n };;\n > visitor2 0 tr |> Seq.take 2;;\n--yielding: 13\n--yielding: 124\nval it : seq<int> = seq [13; 124]\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30861/"
] |
283,589
|
<p>is there a way to change an oracle user's default schema?</p>
<p>I found it in the FAQ that I can alter it in the session, but it's not what I want. E.G. the user at log on always sees another schema as default.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 283814,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 6,
"selected": true,
"text": "CREATE OR REPLACE TRIGGER db_logon\nAFTER logon ON DATABASE WHEN (USER = 'A')\nBEGIN\n execute immediate 'ALTER SESSION SET CURRENT_SCHEMA = B';\nEND;\n"
},
{
"answer_id": 809549,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 4,
"selected": false,
"text": "create or replace trigger set_default_schema\nafter logon on my_user.schema\nbegin\n execute immediate 'alter session set current_schema=NEW_SCHEMA';\nend;\n"
},
{
"answer_id": 12915088,
"author": "Greg",
"author_id": 1750074,
"author_profile": "https://Stackoverflow.com/users/1750074",
"pm_score": 1,
"selected": false,
"text": "create or replace trigger AFTER_LOGON_TSFREL\nAFTER LOGON ON \"TSFRELEASEAPP\".SCHEMA\nBEGIN\n EXECUTE IMMEDIATE 'ALTER SESSION SET current_schema=TSF_RELEASE';\nEND;\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11621/"
] |
283,591
|
<p>I have an website. When the user is logged the session details will loaded.
When the user logged out the session details will abandoned. (Log out by clicking the logout menu)
when the user simply closes the browser then how to destroy the session.</p>
<p>In the next time its get logging with the same session data. I need to avoid this.</p>
|
[
{
"answer_id": 283622,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 0,
"selected": false,
"text": "< sessionState ... timeout=\"5\" />\n"
},
{
"answer_id": 4586469,
"author": "Sunil Gosaliya",
"author_id": 561500,
"author_profile": "https://Stackoverflow.com/users/561500",
"pm_score": 0,
"selected": false,
"text": "try\n {\n Session[\"Admin\"] = null;\n Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));\n Response.Cache.SetCacheability(HttpCacheability.NoCache);\n Response.Cache.SetNoStore();\n Session.Abandon();\n Session.Clear(); \n Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);\n Response.Redirect(\"Dep_NewUserCreate.aspx\");\n\n\n }\n catch(Exception ExLink)\n {\n Response.Redirect(\"Dep_NewUserCreate.aspx\");\n }\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
283,593
|
<p>Currently, my Objective C classes use C++ objects by doing a <code>new</code> when the owner is created, and calling <code>delete</code> when it is destroyed. But is there another way? I'd like to be able to declare, say, an <code>auto_ptr</code> whose scope lasts the duration of the Objective C class' lifetime.</p>
|
[
{
"answer_id": 284770,
"author": "wisequark",
"author_id": 33159,
"author_profile": "https://Stackoverflow.com/users/33159",
"pm_score": 1,
"selected": false,
"text": "delete"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9476/"
] |
283,608
|
<p>I have quite a large list of words in a txt file and I'm trying to do a regex find and replace in Notepad++. I need to add a string before each line and after each line.. So that:</p>
<pre>
wordone
wordtwo
wordthree
</pre>
<p>become</p>
<pre>
able:"wordone"
able:"wordtwo"
able:"wordthree"
</pre>
<p>How can I do this?</p>
|
[
{
"answer_id": 283613,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 9,
"selected": true,
"text": "Search = ^([A-Za-z0-9]+)$\nReplace = able:\"\\1\"\n Search = ^(.+)$\n ^ $ \\1"
},
{
"answer_id": 44923194,
"author": "Mukul Aggarwal",
"author_id": 4544947,
"author_profile": "https://Stackoverflow.com/users/4544947",
"pm_score": 5,
"selected": false,
"text": "Find: \\w.+\nReplace: able:\"$&\"\n $&"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
283,632
|
<p>I followed the commonly-linked tip for reducing an application to the system tray : <a href="http://www.developer.com/net/csharp/article.php/3336751" rel="noreferrer">http://www.developer.com/net/csharp/article.php/3336751</a> Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load event, but it does nothing.</p>
<p>Edit : I could, as a poster suggested, modify the shortcut properties, but I'd rather use code : I don't have complete control over every computer the soft is installed on.</p>
<p>I don't want to remove it completely from everywhere except the systray, I just want it to start minimized.</p>
<p>Any ideas ?</p>
<p>Thanks</p>
|
[
{
"answer_id": 283640,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "NotifyIcon using System;\nusing System.Windows.Forms;\nclass MyForm : Form\n{\n NotifyIcon sysTray;\n\n MyForm()\n {\n sysTray = new NotifyIcon();\n sysTray.Icon = System.Drawing.SystemIcons.Asterisk;\n sysTray.Visible = true;\n sysTray.Text = \"Hi there\";\n sysTray.MouseClick += delegate { MessageBox.Show(\"Boo!\"); };\n\n ShowInTaskbar = false;\n FormBorderStyle = FormBorderStyle.SizableToolWindow;\n Opacity = 0;\n WindowState = FormWindowState.Minimized;\n }\n\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.Run(new MyForm());\n }\n}\n protected override void OnLoad(EventArgs e)\n{\n base.OnLoad(e);\n IntPtr handle = this.Handle;\n int currentStyle = GetWindowLong(handle, GWL_EXSTYLE);\n SetWindowLong(handle, GWL_EXSTYLE, currentStyle | WS_EX_TOOLWINDOW);\n}\nprivate const int GWL_EXSTYLE = -20, WS_EX_TOOLWINDOW = 0x00000080;\n[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\nprivate static extern int SetWindowLong(IntPtr window, int index, int value);\n[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\nprivate static extern int GetWindowLong(IntPtr window, int index);\n"
},
{
"answer_id": 283649,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 4,
"selected": false,
"text": "static class Program\n{\n [STAThread]\n static void Main()\n {\n NotifyIcon icon = new NotifyIcon();\n icon.Icon = System.Drawing.SystemIcons.Application;\n icon.Click += delegate { MessageBox.Show(\"Bye!\"); icon.Visible = false; Application.Exit(); };\n icon.Visible = true;\n Application.Run();\n }\n}\n"
},
{
"answer_id": 283683,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 6,
"selected": true,
"text": "Application.Run(new Form1());\n Application.Run Form1 form = new Form1();\nApplication.Run();\n Application.ExitThread() FormClosed private void Form1_FormClosed(object sender, FormClosedEventArgs e)\n{\n Application.ExitThread();\n}\n"
},
{
"answer_id": 283855,
"author": "rjrapson",
"author_id": 1616,
"author_profile": "https://Stackoverflow.com/users/1616",
"pm_score": 1,
"selected": false,
"text": "Public mobNotifyIcon As NotifyIcon\nPublic WithEvents mobContextMenu As ContextMenu\n\nPublic Sub Main()\n\n mobContextMenu = New ContextMenu\n SetupMenu()\n mobNotifyIcon = New NotifyIcon()\n With mobNotifyIcon\n .Icon = My.Resources.NotifyIcon\n .ContextMenu = mobContextMenu\n .BalloonTipText = String.Concat(\"Monitor the EDS Transfer Service\", vbCrLf, \"Right click icon for menu\")\n .BalloonTipIcon = ToolTipIcon.Info\n .BalloonTipTitle = \"EDS Transfer Monitor\"\n .Text = \"EDS Transfer Service Monitor\"\n AddHandler .MouseClick, AddressOf showBalloon\n .Visible = True\n End With\n Application.Run()\nEnd Sub\n\nPrivate Sub SetupMenu()\n With mobContextMenu\n\n .MenuItems.Add(New MenuItem(\"Configure\", New EventHandler(AddressOf Config)))\n .MenuItems.Add(\"-\")\n .MenuItems.Add(New MenuItem(\"Start\", New EventHandler(AddressOf StartService)))\n .MenuItems.Add(New MenuItem(\"Stop\", New EventHandler(AddressOf StopService)))\n .MenuItems.Add(\"-\")\n .MenuItems.Add(New MenuItem(\"Exit\", New EventHandler(AddressOf ExitController)))\n End With\n GetServiceStatus()\nEnd Sub\n Private Sub Config(ByVal sender As Object, ByVal e As EventArgs)\n Using cs As New ConfigureService\n cs.Show()\n End Using\n\nEnd Sub\n"
},
{
"answer_id": 284446,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Imports System.threading \nImports System.Runtime.InteropServices \nImports System.Windows.Forms\n\n\nPublic Class Class1\n\n <System.STAThread()> _\n Public Shared Sub Main()\n\n Try\n System.Windows.Forms.Application.EnableVisualStyles()\n System.Windows.Forms.Application.DoEvents()\n System.Windows.Forms.Application.Run(New Class2)\n Catch invEx As Exception\n\n Application.Exit()\n\n End Try\n\n\n End Sub 'Main End Class \n Imports System.Windows.Forms \nImports System.drawing\n\nPublic Class Class2\n Inherits System.Windows.Forms.ApplicationContext\n\n Private WithEvents f As New System.Windows.Forms.Form\n Private WithEvents nf As New System.Windows.Forms.NotifyIcon\n\n Public Sub New()\n\n f.Size = New Drawing.Size(50, 50)\n f.StartPosition = FormStartPosition.CenterScreen\n f.WindowState = Windows.Forms.FormWindowState.Minimized\n f.ShowInTaskbar = False\n nf.Visible = True\n nf.Icon = New Icon(\"f:\\TP.ico\")\n End Sub\n\n\n Private Sub nf_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles nf.DoubleClick\n If f.WindowState <> Windows.Forms.FormWindowState.Minimized Then\n f.WindowState = Windows.Forms.FormWindowState.Minimized\n f.Hide()\n Else\n f.WindowState = Windows.Forms.FormWindowState.Normal\n f.Show()\n End If\n End Sub\n\n Private Sub f_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) Handles f.FormClosed\n Application.Exit()\n End Sub End Class\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6776/"
] |
283,636
|
<p>We need to set up a secure certificate on an Apache reverse proxy.
We've been advised that we need to use a virtual host directive.</p>
<p>I've looked these up in the O'Reilly book bit can't find any examples that pick up https specifically.</p>
<p>Does anyone have any examples of config snippets to do this?</p>
|
[
{
"answer_id": 283663,
"author": "f4nt",
"author_id": 14838,
"author_profile": "https://Stackoverflow.com/users/14838",
"pm_score": 2,
"selected": false,
"text": "<IfModule mod_ssl.c>\n SSLProxyEngine On\n ProxyPreserveHost On\n RewriteRule ^/whatever(.*)$ https://otherhost/whatever$1 [P]\n</IfModule>\n"
},
{
"answer_id": 283665,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 3,
"selected": true,
"text": "<VirtualHost IP.ADDRESS.HERE:443>\n DocumentRoot /web/domain.com/www/htdocs\n\n ServerName www.domain.com\n ServerAdmin server@domain.com\n\n SSLEngine on\n SSLCertificateFile /usr/local/etc/apache/ssl.crt/www.domain.com.crt\n SSLCertificateKeyFile /usr/local/etc/apache/ssl.key/www.domain.com.key\n\n ErrorLog \"/var/logs/domain.com/error_log\"\n CustomLog \"|/usr/local/sbin/cronolog /var/logs/domain.com/%Y/%m/access_log\" combined\n</VirtualHost>\n <VirtualHost /> <VirtualHost /> LoadModule ssl_module libexec/apache/libssl.so\n...\nAddModule mod_ssl.c\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39447/"
] |
283,637
|
<p>Can I utilise the new functionality provided by the new JavaFX APIs directly from Java to the same extent as I would be able to using JavaFX Script?</p>
<p>Are all the underlying JavaFX APIs purely Java or JavaFX Script or a mix?</p>
|
[
{
"answer_id": 716236,
"author": "Marco Luglio",
"author_id": 14263,
"author_profile": "https://Stackoverflow.com/users/14263",
"pm_score": 1,
"selected": false,
"text": "import java.awt.Color;\nimport java.awt.Paint;\nimport java.awt.geom.Point2D;\n\nimport javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\nimport com.sun.scenario.scenegraph.JSGPanel;\nimport com.sun.scenario.scenegraph.SGGroup;\nimport com.sun.scenario.scenegraph.fx.FXText;\n\n\n\npublic class HelloWorldScenario101 implements Runnable {\n\n\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new HelloWorldScenario101());\n }\n\n\n\n public HelloWorldScenario101() {\n //\n }\n\n\n\n @Override\n public void run() {\n\n this.frame = new JFrame();\n this.panel = new JSGPanel();\n this.text = new FXText();\n this.paint = new Color(255, 0, 0, 255);\n\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setTitle(\"Hello World\");\n frame.add(this.panel);\n frame.setContentPane(this.panel);\n scene = new SGGroup();\n this.text.setText(\"Hello World\");\n this.text.setFillPaint(this.paint);\n this.text.setLocation(new Point2D.Float(10, 10));\n this.scene.add(this.text);\n this.panel.setScene(scene);\n frame.pack();\n frame.setLocationByPlatform(true);\n frame.setVisible(true);\n\n }\n\n\n\n private JFrame frame;\n\n private JSGPanel panel;\n\n private SGGroup scene;\n\n private FXText text;\n\n private Paint paint;\n\n\n\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
283,645
|
<p>I have a python list, say l</p>
<pre><code>l = [1,5,8]
</code></pre>
<p>I want to write a sql query to get the data for all the elements of the list, say</p>
<pre><code>select name from students where id = |IN THE LIST l|
</code></pre>
<p>How do I accomplish this?</p>
|
[
{
"answer_id": 283706,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 4,
"selected": false,
"text": "myquery = \"select name from studens where id in (%s)\" % \",\".join(map(str,mylist))\n"
},
{
"answer_id": 283713,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": false,
"text": "select name from studens where id in (1, 5, 8)\n l = [1, 5, 8]\nsql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')'\n l = [1, 5, 8]\nsql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')'\n select name from studens where id = 1 or id = 5 or id = 8\n sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l))\n"
},
{
"answer_id": 283801,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 8,
"selected": true,
"text": "placeholder= '?' # For SQLite. See DBAPI paramstyle.\nplaceholders= ', '.join(placeholder for unused in l)\nquery= 'SELECT name FROM students WHERE id IN (%s)' % placeholders\ncursor.execute(query, l)\n"
},
{
"answer_id": 4233213,
"author": "jimhark",
"author_id": 514485,
"author_profile": "https://Stackoverflow.com/users/514485",
"pm_score": 3,
"selected": false,
"text": "placeholder= '?' # For SQLite. See DBAPI paramstyle.\nplaceholders= ', '.join(placeholder for unused in l)\nquery= 'SELECT name FROM students WHERE id IN (%s)' % placeholders\ncursor.execute(query, l)\n placeholders= ', '.join(placeholder for unused in l)\n placeholders= ', '.join(placeholder*len(l))\n l __len__ placeholders= ', '.join([placeholder]*len(l))\n"
},
{
"answer_id": 27145241,
"author": "Ximix",
"author_id": 2592043,
"author_profile": "https://Stackoverflow.com/users/2592043",
"pm_score": 2,
"selected": false,
"text": ">>> random_ids = [1234,123,54,56,57,58,78,91]\n>>> cursor.execute(\"create table test (id)\")\n>>> for item in random_ids:\n cursor.execute(\"insert into test values (%d)\" % item)\n>>> sublist = [56,57,58]\n>>> cursor.execute(\"select id from test where id in %s\" % str(tuple(sublist)).replace(',)',')'))\n>>> a = cursor.fetchall()\n>>> a\n[(56,), (57,), (58,)]\n cursor.execute(\"select id from test where id in (%s)\" % ('\"'+'\", \"'.join(l)+'\"'))\n"
},
{
"answer_id": 39024751,
"author": "pgalilea",
"author_id": 1510734,
"author_profile": "https://Stackoverflow.com/users/1510734",
"pm_score": 0,
"selected": false,
"text": "select name from studens where id in (1, 5, 8)\n my_list = [1, 5, 8]\ncur.execute(\"select name from studens where id in %s\" % repr(my_list).replace('[','(').replace(']',')') )\n"
},
{
"answer_id": 40737575,
"author": "ALLSYED",
"author_id": 5270699,
"author_profile": "https://Stackoverflow.com/users/5270699",
"pm_score": 5,
"selected": false,
"text": "l = [1,5,8]\n\nl = tuple(l)\n\nparams = {'l': l}\n\ncursor.execute('SELECT * FROM table where id in %(l)s',params)\n"
},
{
"answer_id": 49679494,
"author": "Amir Imani",
"author_id": 6509765,
"author_profile": "https://Stackoverflow.com/users/6509765",
"pm_score": 7,
"selected": false,
"text": "tuple t = tuple(l)\nquery = \"select name from studens where id IN {}\".format(t)\n"
},
{
"answer_id": 51091831,
"author": "Roland Mechler",
"author_id": 10008063,
"author_profile": "https://Stackoverflow.com/users/10008063",
"pm_score": 0,
"selected": false,
"text": "l = [1,5,8]\n\nget_operator = lambda x: '=' if len(x) == 1 else 'IN'\nget_value = lambda x: int(x[0]) if len(x) == 1 else x\n\nquery = 'SELECT * FROM table where id ' + get_operator(l) + ' %s'\n\ncursor.execute(query, (get_value(l),))\n"
},
{
"answer_id": 54646596,
"author": "Rishabh Jain",
"author_id": 6692436,
"author_profile": "https://Stackoverflow.com/users/6692436",
"pm_score": 2,
"selected": false,
"text": "placeholders= ', '.join(\"'{\"+str(i)+\"}'\" for i in range(len(l)))\nquery=\"select name from students where id (%s)\"%placeholders\nquery=query.format(*l)\ncursor.execute(query)\n"
},
{
"answer_id": 55802128,
"author": "Omar Omeiri",
"author_id": 11127541,
"author_profile": "https://Stackoverflow.com/users/11127541",
"pm_score": 2,
"selected": false,
"text": "lst = [1,2,3,a,b,c]\n\nquery = f\"\"\"SELECT * FROM table WHERE IN {str(lst)[1:-1}\"\"\"\n"
},
{
"answer_id": 59399870,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 2,
"selected": false,
"text": "ids = [1,2,3]\ncur.execute(\n \"SELECT * FROM foo WHERE id IN %s\",\n [tuple(ids)])\n IN tuple list = ANY cur.execute(\n \"SELECT * FROM foo WHERE id = ANY (%s)\",\n [list(ids)])\n"
},
{
"answer_id": 62024363,
"author": "user13476428",
"author_id": 13476428,
"author_profile": "https://Stackoverflow.com/users/13476428",
"pm_score": 2,
"selected": false,
"text": "l = [1] # or [1,2,3]\n\nquery = \"SELECT * FROM table WHERE id IN :l\"\nparams = {'l' : tuple(l)}\ncursor.execute(query, params)\n :var"
},
{
"answer_id": 63620667,
"author": "raj",
"author_id": 11040181,
"author_profile": "https://Stackoverflow.com/users/11040181",
"pm_score": 1,
"selected": false,
"text": "t = str(tuple(l))\nif t[-2] == ',':\n t= t.replace(t[-2],\"\")\nquery = \"select name from studens where id IN {}\".format(t)\n"
},
{
"answer_id": 64024678,
"author": "Greed Ruler",
"author_id": 4830065,
"author_profile": "https://Stackoverflow.com/users/4830065",
"pm_score": 2,
"selected": false,
"text": "query = \"Select * from hr_employee WHERE id in \" % tuple(employee_ids) if len(employee_ids) != 1 else \"(\"+ str(employee_ids[0]) + \")\"\n"
},
{
"answer_id": 64998540,
"author": "citynorman",
"author_id": 3140992,
"author_profile": "https://Stackoverflow.com/users/3140992",
"pm_score": 2,
"selected": false,
"text": "repr(tuple(map(str, l))) l = ['a','b','c']\nsql = f'''\n\nselect name \nfrom students \nwhere id in {repr(tuple(map(str, l)))}\n'''\nprint(sql)\n select name from students where id in ('a', 'b', 'c') dates_str = ','.join([f'DATE {repr(s)}' for s in ['2020-11-24', '2020-12-28']])\ndates_str = f'({dates_str})'\n\nsql_cmd = f'''\nselect *\nfrom students \nwhere \nand date in {dates_str}\n'''\n select * from students where and date in (DATE '2020-11-24',DATE '2020-12-28')"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2220518/"
] |
283,646
|
<p>I have just converted a project from Visual Studio 2003 to 2005 and although most of it 'converted' fine, I have a series of STL errors from the following line:</p>
<pre><code>void SomeFn( std::vector<CSomeObject*>::iterator it,
std::vector<CSomeObject*>::iterator itBegin = NULL,
std::vector<CSomeObject*>::iterator itEnd = NULL );
</code></pre>
<p>The Visual Studio error is as follows:</p>
<pre><code>c:\<path>\Headerfile.h(20) : error C2440: 'default argument' : cannot convert from 'int' to 'std::_Vector_iterator<_Ty,_Alloc>'
with
[
_Ty=CObject *,
_Alloc=std::allocator<CObject *>
]
No constructor could take the source type, or constructor overload resolution was ambiguous
</code></pre>
<p>I can't see anything wrong with that code and it worked perfectly in VS 2003. Any ideas?</p>
|
[
{
"answer_id": 283660,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 2,
"selected": false,
"text": "std::vector<T>::iterator T * NULL NULL 0 std::vector<CSomeObject*>::iterator itBegin = std::vector<CSomeObject*>::iterator()\n"
},
{
"answer_id": 283693,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 5,
"selected": true,
"text": "typedef std::vector<CSomeObject*> myvector_t;\nvoid SomeFn( myvector_t::iterator it,\n myvector_t::iterator itBegin = myvector_t::iterator(),\n myvector_t::iterator itEnd = myvector_t::iterator() );\n it itBegin itEnd itBegin itEnd typedef std::vector<CSomeObject*> myvector_t;\nvoid SomeFn( myvector_t::iterator it,\n myvector_t::iterator itBegin,\n myvector_t::iterator itEnd );\nvoid SomeFn( myvector_t::iterator it ); // No begin/end arguments\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
283,661
|
<p>Since a few days ago, MySQL server on my Windows machine was not successful on closing itself. I found multiple instance of these lines in the MySQL error log:</p>
<pre><code>InnoDB: Operating system error number 32 in a file operation.
InnoDB: The error means that another program is using InnoDB's files.
InnoDB: This might be a backup or antivirus software or another instance
InnoDB: of MySQL. Please close it to get rid of this error.
</code></pre>
<p>I have plenty of free spaces, the server is installed for months, the version is 5.1.22-rc-community-log on Windows XP SP3, and I have used only one Windows account to create and execute MySQL service.</p>
<p>Following Greg's answer, I found through <code>ProcessExplorer</code> that there's another MySQL service running with a different name. I kill it and all run fine.</p>
|
[
{
"answer_id": 11202882,
"author": "Anadi Kumar",
"author_id": 1482004,
"author_profile": "https://Stackoverflow.com/users/1482004",
"pm_score": 2,
"selected": false,
"text": "cd E:\\apps\\db\\mysql-5.5.25-win32\\bin mysqld --install MySQL mysqladmin -u root start"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8404/"
] |
283,669
|
<p>I have a console application project in C# 2.0 that needs to write something to the screen in a while loop. I do not want the screen to scroll because using Console.Write or Console.Writeline method will keep displaying text on console screen incremently and thus it starts scrolling.</p>
<p>I want to have the string written at the same position. How can i do this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 49099413,
"author": "fishjd",
"author_id": 321747,
"author_profile": "https://Stackoverflow.com/users/321747",
"pm_score": 2,
"selected": false,
"text": " /// <summary>\n /// Writes a string at the x position, y position = 1;\n /// Tries to catch all exceptions, will not throw any exceptions. \n /// </summary>\n /// <param name=\"s\">String to print usually \"*\" or \"@\"</param>\n /// <param name=\"x\">The x postion, This is modulo divided by the window.width, \n /// which allows large numbers, ie feel free to call with large loop counters</param>\n protected static void WriteProgress(string s, int x) {\n int origRow = Console.CursorTop;\n int origCol = Console.CursorLeft;\n // Console.WindowWidth = 10; // this works. \n int width = Console.WindowWidth;\n x = x % width;\n try {\n Console.SetCursorPosition(x, 1);\n Console.Write(s);\n } catch (ArgumentOutOfRangeException e) {\n\n } finally {\n try {\n Console.SetCursorPosition(origCol, origRow);\n } catch (ArgumentOutOfRangeException e) {\n }\n }\n }\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20933/"
] |
283,672
|
<p>I have a user who gets an error from ajax calls on our site.</p>
<p>The error is pasted below. </p>
<p>They get the error in FF3 Windows, but not IE.</p>
<p>Based on some searching it seems this issue is often caused by the client protocol squid (you'll notice at the end of the error, squid is mentioned).</p>
<p>My ajax code is the same used here: <a href="http://www.w3schools.com/Ajax/ajax_browsers.asp" rel="nofollow noreferrer">http://www.w3schools.com/Ajax/ajax_browsers.asp</a></p>
<p>Any ideas?</p>
<pre><code>ERROR
The requested URL could not be retrieved
While trying to process the request:
POST /library/cart/cart_ajax.php?action=refreshCartWidget&qty=dontuse& HTTP/1.1
Host: mydomain.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: identity,gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: Close
Referer: http://mydomain.com/library
Pragma: no-cache
Cache-Control: no-cache
The following error was encountered:
Invalid Request
Some aspect of the HTTP Request is invalid. Possible problems:
Missing or unknown request method
Missing URL
Missing HTTP Identifier (HTTP/1.0)
Request is too large
Content-Length missing for POST or PUT requests
Illegal character in hostname; underscores are not allowed
Your cache administrator is webmaster.
Generated Wed, 12 Nov 2008 09:28:58 GMT by ipwal3.osi-tech.com (squid/2.6.STABLE17)
</code></pre>
|
[
{
"answer_id": 283686,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "$.post(\n '/the/url/to/post/to',\n { some: data },\n function(data) { alert(data); }\n);\n PUT POST GET DELETE HEAD Content-Length PUT POST"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,679
|
<p>I'm not looking for the usual answer like Web-services. I'm looking for a light solution to be run in the same machine.</p>
<p>Edit: I'm looking for way in Java to call .NET methods</p>
|
[
{
"answer_id": 11683074,
"author": "Mechanical snail",
"author_id": 319931,
"author_profile": "https://Stackoverflow.com/users/319931",
"pm_score": 1,
"selected": false,
"text": "javac ikvmstub mscorlib\n mscorlib.jar mscorlib.dll import cli.System.IO.Directory;\npublic class IKVMTest {\n public static void main(String[] args) {\n for(String file : Directory.GetFiles(\".\")) // From .NET standard library\n System.out.println(file); // From Java standard library\n }\n}\n cli. cli.System System javac -classpath mscorlib.jar IKVMTest.java\n class ikvm IKVMTest\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36678/"
] |
283,701
|
<p>What are best practices with regards to C and C++ coding standards? Should developers be allowed to willy-nilly mix them together. Are there any complications when linking C and C++ object files.</p>
<p>Should things like socket libraries that traditionally is written in C remain in C and kept in seperate source files? That is keeping c code in .c files and c++ code in .cpp files.
When mixing c and C++ after being parsed with g++ will there be any performance penalties, since typesafe checks are not done in C? but are in C++. Would would be the best way to link C and C++ source code files.</p>
|
[
{
"answer_id": 283716,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 3,
"selected": false,
"text": "extern \"C\" #if defined( __cplusplus )\nextern \"C\" {\n#endif\n\nextern int myfunc( const char *param, int another_one );\n\n#if defined( __cplusplus )\n}\n#endif\n #if extern \"C\" extern \"C\" {\n#include \"myfuncheader.h\"\n}\n"
},
{
"answer_id": 283722,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 2,
"selected": false,
"text": "dynamic_cast"
},
{
"answer_id": 283810,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "-fexceptions"
},
{
"answer_id": 283841,
"author": "David Allan Finch",
"author_id": 27417,
"author_profile": "https://Stackoverflow.com/users/27417",
"pm_score": 1,
"selected": false,
"text": "/* c header */\n\nstruct CData\n { /* stuff */ };\n\nvoid init( CData* data );\nvoid fini( CData* data );\nint getSomething( CData* data );\nvoid doSomething( CData* data, int val );\n\n// c++ header\n\nextern \"C\" {\n#include cdata.h\n};\n\nclass CppData : private CData\n {\n public:\n CppData() { ::init( (CData*)this ); }\n ~CppData() { ::fini( (CData*)this ); }\n int getSomething() { return ::getSomething( (CData*)this ); }\n void doSomething( int val ) { :: doSomething( (CData*)this, val ); }\n };\n"
},
{
"answer_id": 285063,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "extern \"c\"\n{\n int nice_c_function_interface\n (\n void\n )\n {\n int returnStatus;\n\n try\n {\n returnStatus = nice_cpp_function();\n }\n catch (NiceCppException& that)\n {\n returnStatus = that.failure_code(); \n }\n catch (...)\n {\n cerr << \"Oh Worse! an unexpected unknown exception\" << endl;\n\n returnStatus = -1; // Horrible unknown failure\n }\n\n return returnStatus;\n }\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7362/"
] |
283,707
|
<p>Is there a way to find the size of a file object that is currently open?</p>
<p>Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.</p>
|
[
{
"answer_id": 283718,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "fstat"
},
{
"answer_id": 283719,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 8,
"selected": true,
"text": "$ ls -la chardet-1.0.1.tgz\n-rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz\n$ python\nPython 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)\n[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> f = open('chardet-1.0.1.tgz','rb')\n>>> f.seek(0, os.SEEK_END)\n>>> f.tell()\n179218L\n >>> import os\n>>> os.fstat(f.fileno()).st_size\n179218L\n>>> \n f.seek(0, os.SEEK_END) f.tell() f.seek(0, os.SEEK_END)"
},
{
"answer_id": 283725,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 4,
"selected": false,
"text": "current_size = f.tell()\n os.fstat"
},
{
"answer_id": 38992375,
"author": "vestronge",
"author_id": 6725474,
"author_profile": "https://Stackoverflow.com/users/6725474",
"pm_score": 1,
"selected": false,
"text": "with open(file_path, 'rb') as x:\n body = StringIO()\n body.write(x.read())\n body.seek(0, 0)\n body body.read() body.len"
},
{
"answer_id": 73214956,
"author": "darda",
"author_id": 149506,
"author_profile": "https://Stackoverflow.com/users/149506",
"pm_score": 0,
"selected": false,
"text": "name os.stat import io\ndef seek_size(f):\n pos = f.tell()\n f.seek(0, io.SEEK_END)\n size = f.tell()\n f.seek(pos) # back to where we were\n return size\n os.stat(f.name)"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36312/"
] |
283,727
|
<p>I've spent hours trying to get my code to work, its a rats nest of if/elses. Basically I want to check a country name against these two arrays:</p>
<pre><code>//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("eire","hispaniola");
</code></pre>
<p>and thats it. </p>
<p>Its sending me batty, and to be honest I'm embarassed to show you my code. Lets just say it has 2 if statements, 2 else statements and 2 foreach loops. Its a blooming mess, and I was hoping someone can dumbfound me by showing me a good way of doing this? I expect there is a way using only 1 line of code, or something sickening like that.
Thank you.</p>
|
[
{
"answer_id": 283742,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 2,
"selected": false,
"text": "$countryKey = strtolower($country);\nif (in_array($countryKey, $keywords)) {\n $country = 'The' . $country;\n} else if (in_array($countryKey, $exceptions) && stripos($country, 'the ') === 0) {\n $country = substr($country, 4);\n}\n"
},
{
"answer_id": 283743,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "\",bahamas,island,kingdom,republic,maldives,netherlands,isle of man,ivory,philippines,seychelles,usa,\"\n"
},
{
"answer_id": 283746,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 1,
"selected": false,
"text": "if(in_array($country, $keywords)) {\n // add 'the'\n} elseif(in_array($country, $exceptions)) {\n // remove 'the'\n}\n"
},
{
"answer_id": 283777,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "//if its in this array add a 'THE' \n$keywords = array(\"bahamas\",\"island\",\"kingdom\",\"republic\",\"maldives\",\"netherlands\",\n \"isle of man\",\"ivory\",\"philippines\",\"seychelles\",\"usa\");\n//if its in this array, take THE off!\n$exceptions = array(\"the eire\",\"the hispaniola\");\n\n$countryKey = strtolower($country);\nif (in_array($countryKey, $keywords)) {\n $country = 'The ' . $country;\n} else if (in_array($countryKey, $exceptions)) {\n $country = substr($country, 4);\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
283,728
|
<p>I need to create a BAT file to run an application through telnet, but as far as I know there is no way to do this on DOS. Telnet does not allow any command to be sent to the remote machine at the very instant of the connection, and each subsequent command in the BAT file would only be executed after telnet stops. This hypothetical piece of code illustrates what I want to do:</p>
<pre><code>telnet 100.99.98.1 "C:\Application\app.exe -a -b -c"
</code></pre>
<p>And that would run the app.exe on the machine 100.99.98.1 with three parameters. Despite my efforts, nothing worked. Is there a way to do that?</p>
<p>Tks,</p>
<p>Pedrin Batista</p>
|
[
{
"answer_id": 283744,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 0,
"selected": false,
"text": "start"
},
{
"answer_id": 283747,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "echo \"c:\\application\\app.exe -a -b -c\" | telnet 100.99.98.1\n"
},
{
"answer_id": 283753,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "telnet 100.99.98.1 <someScript\n C:\\Application\\app.exe -a -b -c"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36183/"
] |
283,737
|
<p>I have an ASP.NET 1.1 application that uses the following code to write out a file in the response:</p>
<pre><code>Dim objStream As Object
objStream = Server.CreateObject("ADODB.Stream")
objStream.open()
objStream.type = 1
objStream.loadfromfile(localfile)
Response.BinaryWrite(objStream.read)
</code></pre>
<p>This code is called by a pop up window that displays this file or gives a open/save dialog in Internet Explorer. The problem is, that it seems to work fine in IE6 but in IE7 the pop up opens and then closes without displaying the file. Any one know whats wrong?</p>
|
[
{
"answer_id": 1060550,
"author": "pedrofernandes",
"author_id": 127891,
"author_profile": "https://Stackoverflow.com/users/127891",
"pm_score": 0,
"selected": false,
"text": "strFilename = Server.MapPath(\"/App_Upload/\" & strFilename) \n\nWith Response\n .AddHeader(\"Content-Type\", \"binary/octet-stream\")\n .AddHeader(\"Content-Disposition\", \"attachment; filename=\" & strFilename & \";\")\n .WriteFile(strFilename)\n .End()\nEnd With\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] |
283,740
|
<p>I am using the Zend Framework.</p>
<p>I have a controller named 'UserController' that has a public function displayAction().</p>
<p>I would like to know how I can get that action method to use a different viewer than the default display.phtml.</p>
<p>Any help is appreciated.</p>
|
[
{
"answer_id": 283784,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 5,
"selected": true,
"text": "$this->render('actionName');\n $this->renderScript('path/to/viewscript.phtml');\n render() renderScript()"
},
{
"answer_id": 10469195,
"author": "Brian Vanderbusch",
"author_id": 1106939,
"author_profile": "https://Stackoverflow.com/users/1106939",
"pm_score": 1,
"selected": false,
"text": "$this->_helper->viewRenderer('action');\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15052/"
] |
283,749
|
<p>At work, I'm frequently working on projects where numerous properties of certain objects have to be set during their construction or early during their lifetime. For the sake of convenience and readability, I often use the <code>With</code> statement to set these properties. I find that</p>
<pre><code>With Me.Elements
.PropertyA = True
.PropertyB = "Inactive"
' And so on for several more lines
End With
</code></pre>
<p>Looks much better than</p>
<pre><code>Me.Elements.PropertyA = True
Me.Elements.PropertyB = "Inactive"
' And so on for several more lines
</code></pre>
<p>for very long statements that simply set properties.</p>
<p>I've noticed that there are some issues with using <code>With</code> while debugging; however, <strong>I was wondering if there were any compelling reasons to avoid using <code>With</code> in practice</strong>? I've always assumed the code generated via the compiler for the above two cases is basically the same which is why I've always chosen to write what I feel to be more readable. </p>
|
[
{
"answer_id": 283785,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "var x = new Whatever { PropertyA=true, PropertyB=\"Inactive\" };\n PropertyA = True\nPropertyB = \"Inactive\"\n"
},
{
"answer_id": 283820,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 7,
"selected": true,
"text": "UserHandler.GetUser.First.User.FirstName=\"Stefan\"\nUserHandler.GetUser.First.User.LastName=\"Karlsson\"\nUserHandler.GetUser.First.User.Age=\"39\"\nUserHandler.GetUser.First.User.Sex=\"Male\"\nUserHandler.GetUser.First.User.Occupation=\"Programmer\"\nUserHandler.GetUser.First.User.UserID=\"0\"\n....and so on\n With UserHandler.GetUser.First.User\n .FirstName=\"Stefan\"\n .LastName=\"Karlsson\"\n .Age=\"39\"\n .Sex=\"Male\"\n .Occupation=\"Programmer\"\n .UserID=\"0\"\nend with\n dim myuser as user =UserHandler.GetUser.First.User\nmyuser.FirstName=\"Stefan\"\nmyuser.LastName=\"Karlsson\"\nmyuser.Age=\"39\"\nmyuser.Sex=\"Male\"\nmyuser.Occupation=\"Programmer\"\nmyuser.UserID=\"0\"\n"
},
{
"answer_id": 283853,
"author": "ljorquera",
"author_id": 9132,
"author_profile": "https://Stackoverflow.com/users/9132",
"pm_score": 3,
"selected": false,
"text": "UserHandler.GetUser.First.User.FirstName=\"Stefan\"\nUserHandler.GetUser.First.User.LastName=\"Karlsson\"\nUserHandler.GetUser.First.User.Age=\"39\"\nUserHandler.GetUser.First.User.Sex=\"Male\"\nUserHandler.GetUser.First.User.Occupation=\"Programmer\"\nUserHandler.GetUser.First.User.UserID=\"0\"\n"
},
{
"answer_id": 284041,
"author": "bart",
"author_id": 19966,
"author_profile": "https://Stackoverflow.com/users/19966",
"pm_score": 2,
"selected": false,
"text": "with with with with"
},
{
"answer_id": 284073,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 5,
"selected": false,
"text": "With Imports System.Text\n\nPublic Class Class1\n Public Sub Foo()\n Dim sb As New StringBuilder\n With sb\n .Append(\"foo\")\n .Append(\"bar\")\n .Append(\"zap\")\n End With\n\n Dim sb2 As New StringBuilder\n sb2.Append(\"foo\")\n sb2.Append(\"bar\")\n sb2.Append(\"zap\")\n End Sub\nEnd Class\n sb2 Append With sb .method public instance void Foo() cil managed\n{\n // Code size 91 (0x5b)\n .maxstack 2\n .locals init ([0] class [mscorlib]System.Text.StringBuilder sb,\n [1] class [mscorlib]System.Text.StringBuilder sb2,\n [2] class [mscorlib]System.Text.StringBuilder VB$t_ref$L0)\n IL_0000: nop\n IL_0001: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor()\n IL_0006: stloc.0\n IL_0007: ldloc.0\n IL_0008: stloc.2\n IL_0009: ldloc.2\n IL_000a: ldstr \"foo\"\n IL_000f: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_0014: pop\n IL_0015: ldloc.2\n IL_0016: ldstr \"bar\"\n IL_001b: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_0020: pop\n IL_0021: ldloc.2\n IL_0022: ldstr \"zap\"\n IL_0027: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_002c: pop\n IL_002d: ldnull\n IL_002e: stloc.2\n IL_002f: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor()\n IL_0034: stloc.1\n IL_0035: ldloc.1\n IL_0036: ldstr \"foo\"\n IL_003b: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_0040: pop\n IL_0041: ldloc.1\n IL_0042: ldstr \"bar\"\n IL_0047: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_004c: pop\n IL_004d: ldloc.1\n IL_004e: ldstr \"zap\"\n IL_0053: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_0058: pop\n IL_0059: nop\n IL_005a: ret\n} // end of method Class1::Foo\n With"
},
{
"answer_id": 10029239,
"author": "phillihp",
"author_id": 232271,
"author_profile": "https://Stackoverflow.com/users/232271",
"pm_score": 4,
"selected": false,
"text": "With myObject\n .Property1 = arg1\n .Property2 = arg2\n...\n"
},
{
"answer_id": 18288030,
"author": "JohnRC",
"author_id": 1992793,
"author_profile": "https://Stackoverflow.com/users/1992793",
"pm_score": 4,
"selected": false,
"text": "Dim AA As AAClass = GetNextAAObject()\nWith AA\n AA = GetNextAAObject()\n\n '// Setting property of original AA instance, not later instance\n .SomeProperty = SomeValue\nEnd With\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20/"
] |
283,751
|
<p>I have the problem, that PHP replaces all spaces with underscores in POST and GET variables.</p>
<p>For example if I have the URL: <code>http://localhost/proxy.php?user name=Max</code>
the browser will convert it to <code>http://localhost/proxy.php?user%20name=Max</code>.</p>
<p>But if I give the $_GET parameters out, the key is not <code>user name</code> but <code>user_name</code> (note the underscore)!</p>
<p>Is there any possibility to change this behaviour?</p>
|
[
{
"answer_id": 283781,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 6,
"selected": true,
"text": "<?php $varname.ext; /* invalid variable name */ ?>\n chr(32) ( ) (space)\nchr(46) (.) (dot)\nchr(91) ([) (open square bracket)\nchr(128) - chr(159) (various)\n"
},
{
"answer_id": 689574,
"author": "Rudi",
"author_id": 83613,
"author_profile": "https://Stackoverflow.com/users/83613",
"pm_score": 3,
"selected": false,
"text": "$_SERVER['QUERY_STRING'] $a_pairs = explode('&', $_SERVER['QUERY_STRING']);\nforeach($a_pairs AS $s_pair){\n $a_pair = explode('=', $s_pair);\n if(count($a_pair) == 1) $a_pair[1] = '';\n\n $a_pair[0] = urldecode($a_pair[0]);\n $a_pair[1] = urldecode($a_pair[1]);\n\n $GLOBALS['_GET'][$a_pair[0]] = $a_pair[1];\n $_GET[$a_pair[0]] = $a_pair[1];\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30724/"
] |
283,752
|
<p>I'm automating a web application (the Mantis bug tracker) and I'm getting an interesting response header from it, called Refresh:</p>
<pre><code>HTTP/1.x 200 OK
...
Refresh: 0;url=my_view_page.php
</code></pre>
<p>It seems to be acting the same way that <a href="http://en.wikipedia.org/wiki/Meta_refresh" rel="noreferrer">meta refresh</a> does, and the meta refresh technique implies that it is an equivalent of a header in HTTP.</p>
<p>Problem is, I can't find any mention of the Refresh header in the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="noreferrer">HTTP standard</a> or any other definitive documentation on how it should be parsed and what the browser should do when it encounters it.</p>
<p>What's going on here?</p>
|
[
{
"answer_id": 283776,
"author": "Loki",
"author_id": 17324,
"author_profile": "https://Stackoverflow.com/users/17324",
"pm_score": 5,
"selected": false,
"text": "<meta http-equiv=\"refresh\" url=\"...\"/> Refresh"
},
{
"answer_id": 59167331,
"author": "Mike",
"author_id": 920404,
"author_profile": "https://Stackoverflow.com/users/920404",
"pm_score": 3,
"selected": false,
"text": "Refresh"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15109/"
] |
283,759
|
<p>I'm converting my applications to Delphi 2009 and faced an intriguing issue with some calls that need to convert a string (wide) to AnsiString.</p>
<p>Here's an example to demonstrate the issue I'm having:</p>
<pre><code>var
s: PAnsiChar;
...
s := PAnsiChar(Application.ExeName);
</code></pre>
<p>With Delphi 2007 and previous versions, s := PChar(Application.ExeName) would return the application exe path.</p>
<p>with Delphi 2009, s := PAnsiChar(Application.ExeName) returns only 'E'.</p>
<p>My guess is that's because I'm converting a unicode string to an ansi string but how can I convert it so that a PAnsiChar gets the full string?</p>
|
[
{
"answer_id": 283773,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 6,
"selected": true,
"text": "s := PAnsiChar(AnsiString(Application.ExeName));\n"
},
{
"answer_id": 283885,
"author": "smartins",
"author_id": 36544,
"author_profile": "https://Stackoverflow.com/users/36544",
"pm_score": 1,
"selected": false,
"text": "function LinkerTimeStamp(const FileName: string): TDateTime;\nvar\n LI: TLoadedImage;\nbegin\n {$IFDEF UNICODE}\n Win32Check(MapAndLoad(PAnsiChar(AnsiString(FileName)), nil, @LI, False, True));\n {$ELSE}\n Win32Check(MapAndLoad(PChar(FileName), nil, @LI, False, True));\n {$ENDIF}\n Result := LI.FileHeader.FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;\n UnMapAndLoad(@LI);\nend;\n"
},
{
"answer_id": 614720,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "PAnsiChar // This function converts a string to a PAnsiChar\n// If the output is not the same, an exception is raised\n// Author: nogabel@hotmail.com\n\nfunction StringToPAnsiChar(stringVar : string) : PAnsiChar;\nVar\n AnsString : AnsiString;\n InternalError : Boolean;\nbegin\n InternalError := false;\n Result := '';\n try\n if stringVar <> '' Then\n begin\n AnsString := AnsiString(StringVar);\n Result := PAnsiChar(PAnsiString(AnsString));\n end;\n Except\n InternalError := true;\n end;\n if InternalError or (String(Result) <> stringVar) then\n begin\n Raise Exception.Create('Conversion from string to PAnsiChar failed!');\n end;\nend;\n"
},
{
"answer_id": 2337315,
"author": "Meka",
"author_id": 281567,
"author_profile": "https://Stackoverflow.com/users/281567",
"pm_score": 3,
"selected": false,
"text": "String RawByteString s: RawByteString;\n\ns := LoadSomeRegularString(usually a string type);\n\nPAnsiChar(s) <<< all fine.\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36544/"
] |
283,763
|
<p>I am reading a .csv file and returning its lines in string array. One of the members is manufacturer, for which I have Toyota, Ford, etc.</p>
<p>I want to sort an array (Can be another collection) of the rows, by the value in manufacturer and alphabetical order.</p>
<p>So I'd have:</p>
<pre><code>28437 Ford Fiesta
328 Honda Civic
34949 Toyota Yaris
</code></pre>
<p>and so forth...</p>
<p>What would be the best way to do this using C# and no database? I say no database because I could insert the csv into a table in a sql server database, and then query it and return the data. But this data is going into a html table built on the fly, which would make the database approach a little long winded.</p>
|
[
{
"answer_id": 283771,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "var cars = lines.Select(line => Car.ParseLine(line))\n .OrderBy(car => car.Manufacturer);\n"
},
{
"answer_id": 283842,
"author": "TToni",
"author_id": 20703,
"author_profile": "https://Stackoverflow.com/users/20703",
"pm_score": 1,
"selected": false,
"text": "Array.Sort(myArray)\n string [] sArray = new string[] { \"fsdhj\", \"FA\", \"FX\", \"fxx\", \"Äbc\" };\n sArray = sArray.OrderBy(s => s.ToLowerInvariant()).ToArray();\n"
},
{
"answer_id": 283845,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "public class Car\n{\n public int Id {get;set;}\n public string Manufacturer {get;set;}\n public string Model {get;set;}\n\n public static Car ParseLine(string line)\n {\n string[] parts = line.Split(DELIMITER);\n return new Car\n {\n Id = int.Parse(parts[0]),\n Manufacturer = parts[1],\n Model = parts[2]\n };\n }\n}\n var query = from line in lines\n let car = Car.ParseLine(line)\n orderby car.Manufacturer\n select car;\n\n var arr = query.ToArray();\n Car[] Array.Sort(arr, (x, y) => string.Compare(x.Manufacturer, y.Manufacturer));\n List<Car> list.Sort((x, y) => string.Compare(x.Manufacturer, y.Manufacturer));\n"
},
{
"answer_id": 283849,
"author": "Todd",
"author_id": 31940,
"author_profile": "https://Stackoverflow.com/users/31940",
"pm_score": 1,
"selected": false,
"text": "List<string> lines = new List<string>\n {\n \"34949 Toyota Yaris\",\n \"328 Honda Civic\",\n \"28437 Ford Fiesta\"\n };\n\nvar sortedLines = lines.OrderBy(line => line.Substring(6, 10));\n// Or make it case insensitive\n// var sortedLines = lines.OrderBy(line => line.Substring(6, 10), StringComparer.InvariantCultureIgnoreCase);\n\nforeach (var line in sortedLines)\n{\n Console.WriteLine(line);\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
283,764
|
<p>In a SQL Server database, I record people's date of birth. Is there an straight-forward method of working out the person's age on a given date using SQL only? </p>
<p>Using <strong>DATEDIFF(YEAR, DateOfBirth, GETDATE())</strong> does not work as this only looks at the year part of the date. For example <strong>DATEDIFF(YEAR, '31 December 2007', '01 January 2008')</strong> returns 1.</p>
|
[
{
"answer_id": 283780,
"author": "scable",
"author_id": 8942,
"author_profile": "https://Stackoverflow.com/users/8942",
"pm_score": 6,
"selected": true,
"text": "DECLARE @BirthDate DATETIME\nDECLARE @CurrentDate DATETIME\n\nSELECT @CurrentDate = '20070210', @BirthDate = '19790519'\n\nSELECT DATEDIFF(YY, @BirthDate, @CurrentDate) - CASE WHEN( (MONTH(@BirthDate)*100 + DAY(@BirthDate)) > (MONTH(@CurrentDate)*100 + DAY(@CurrentDate)) ) THEN 1 ELSE 0 END \n"
},
{
"answer_id": 656799,
"author": "Mark Brittingham",
"author_id": 15592,
"author_profile": "https://Stackoverflow.com/users/15592",
"pm_score": 3,
"selected": false,
"text": "Select CAST(DATEDIFF(hh, [birthdate], GETDATE()) / 8766 AS int) AS Age\n"
},
{
"answer_id": 9085213,
"author": "John Pick",
"author_id": 251034,
"author_profile": "https://Stackoverflow.com/users/251034",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION Age (@BirthDate DATETIME)\nRETURNS INT\nAS\nBEGIN\n DECLARE @AgeOnBirthdayThisYear INT\n DECLARE @BirthdayThisYear DATETIME\n SET @AgeOnBirthdayThisYear = DATEDIFF(year, @BirthDate, GETDATE())\n SET @BirthdayThisYear = DATEADD(year, @AgeOnBirthdayThisYear, @BirthDate)\n RETURN\n @AgeOnBirthdayThisYear\n - CASE WHEN @BirthdayThisYear > GETDATE() THEN 1 ELSE 0 END\nEND\n"
},
{
"answer_id": 12776316,
"author": "Paul",
"author_id": 61335,
"author_profile": "https://Stackoverflow.com/users/61335",
"pm_score": 1,
"selected": false,
"text": "SELECT DATEDIFF(YY, birthdate, GETDATE()) - CASE WHEN( (MONTH(birthdate)*100 + DAY(birthdate)) > (MONTH(GETDATE())*100 + DAY(GETDATE())) ) THEN 1 ELSE 0 END\n"
},
{
"answer_id": 13035623,
"author": "brianary",
"author_id": 54323,
"author_profile": "https://Stackoverflow.com/users/54323",
"pm_score": 1,
"selected": false,
"text": "datediff(year,DateOfBirth,getdate()-datepart(dy,DateOfBirth)+1)\n"
},
{
"answer_id": 21468800,
"author": "user3255222",
"author_id": 3255222,
"author_profile": "https://Stackoverflow.com/users/3255222",
"pm_score": 0,
"selected": false,
"text": "SET @Age = YEAR(@AsOf) - YEAR(@DOB) - 1\nIF MONTH(@AsOf) * 100 + DAY(@AsOf) >= MONTH(@DOB) * 100 + DAY(@DOB)\n SET @Age = @Age + 1\n SET @Age = FLOOR(DATEDIFF(dd,@DOB,@CompareDate)/365.25)\n SELECT dbo.fnGetAge('2/27/2008', '2/27/2012')\n SELECT dbo.fnGetAge('2/27/2008', '2/28/2012')\n SELECT dbo.fnGetAge('2/27/2008', '2/29/2012')\n SELECT dbo.fnGetAge('2/27/2008', '3/1/2012')\n -- 4 4 4 4\n SELECT dbo.fnGetAge('2/28/2008', '2/27/2012')\n SELECT dbo.fnGetAge('2/28/2008', '2/28/2012')\n SELECT dbo.fnGetAge('2/28/2008', '2/29/2012')\n SELECT dbo.fnGetAge('2/28/2008', '3/1/2012')\n -- 3 4 4 4\n SELECT dbo.fnGetAge('2/29/2008', '2/27/2012')\n SELECT dbo.fnGetAge('2/29/2008', '2/28/2012')\n SELECT dbo.fnGetAge('2/29/2008', '2/29/2012')\n SELECT dbo.fnGetAge('2/29/2008', '3/1/2012')\n -- 3 3 4 4\n SELECT dbo.fnGetAge('3/1/2008', '2/27/2012')\n SELECT dbo.fnGetAge('3/1/2008', '2/28/2012')\n SELECT dbo.fnGetAge('3/1/2008', '2/29/2012')\n SELECT dbo.fnGetAge('3/1/2008', '3/1/2012')\n -- 3 3 3 4\n SELECT dbo.fnGetAge('3/1/2007', '2/27/2012')\n SELECT dbo.fnGetAge('3/1/2007', '2/28/2012')\n SELECT dbo.fnGetAge('3/1/2007', '2/29/2012')\n SELECT dbo.fnGetAge('3/1/2007', '3/1/2012')\n -- 4 4 4 5\n SELECT dbo.fnGetAge('3/1/2007', '2/27/2013')\n SELECT dbo.fnGetAge('3/1/2007', '2/28/2013')\n SELECT dbo.fnGetAge('3/1/2007', '3/1/2013')\n SELECT dbo.fnGetAge('2/27/2007', '2/28/2013')\n SELECT dbo.fnGetAge('2/28/2007', '2/28/2014')\n -- 5 5 6 6 7\n"
},
{
"answer_id": 34756768,
"author": "Bony Bathini",
"author_id": 5780328,
"author_profile": "https://Stackoverflow.com/users/5780328",
"pm_score": 0,
"selected": false,
"text": "SELECT Pname, DOB, DATEDIFF(YEAR, DOB, GETDATE()) AS Age\nFROM tablename\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
] |
283,766
|
<p>I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.</p>
<p>In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to *.*. Then, if I select a file that has the .char extension, it won't load, giving the error</p>
<blockquote>
<pre><code>unpickle_file = cPickle.load(char_file)
</code></pre>
<p>ValueError: could not convert string to float</p>
</blockquote>
<p>However, if I create a file that doesn't have the .char extension, that file will load up just fine.</p>
<p>In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.</p>
<hr>
<p><strong>Edit</strong> Here's the save code:</p>
<pre><code>def createSaveFile(self):
"""Create the data files to be saved and save them.
Creates a tuple comprised of a dictionary of general character information
and the character's skills dictionary."""
if self.file_name:
self.save_data = ({'Name':self.charAttribs.name,
<snip>
self.charAttribs.char_skills_dict)
self.file = open(self.file_name, 'w')
cPickle.dump(self.save_data, self.file)
self.file.close()
</code></pre>
<p>Here's the open code:</p>
<pre><code> def getCharFile(self, event): # wxGlade: CharSheet.<event_handler>
"""Retrieve pickled character file from disk."""
wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*"
openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(),
"", wildcard, wx.OPEN | wx.CHANGE_DIR)
if openDialog.ShowModal() == wx.ID_OK:
self.path = openDialog.GetPath()
try:
char_file = open(self.path, "r")
unpickle_file = cPickle.load(char_file)
char_data, char_skills = unpickle_file
self.displayCharacter(char_data, char_skills)
except IOError:
self.importError = wx.MessageDialog(self,
"The character file is not available!",
"Character Import Error", wx.OK | wx.ICON_ERROR)
self.importError.ShowModal()
self.importError.Destroy()
openDialog.Destroy()
</code></pre>
|
[
{
"answer_id": 283802,
"author": "Adam Byrtek",
"author_id": 36656,
"author_profile": "https://Stackoverflow.com/users/36656",
"pm_score": 4,
"selected": true,
"text": "char_file = open('pickle.char', 'rb')\n"
},
{
"answer_id": 283854,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "char_file=open('filename.char','rU')\n char_file = open('filename.char','wb')\ncPickle.dumps(data, char_file)\n"
},
{
"answer_id": 284357,
"author": "John Montgomery",
"author_id": 5868,
"author_profile": "https://Stackoverflow.com/users/5868",
"pm_score": 2,
"selected": false,
"text": "self.file = open(self.file_name, 'w') self.file = open(self.file_name, 'wb') createSaveFile"
},
{
"answer_id": 24923596,
"author": "Hadi",
"author_id": 433261,
"author_profile": "https://Stackoverflow.com/users/433261",
"pm_score": 0,
"selected": false,
"text": "dos2unix pickle.char\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
283,812
|
<p>With reference to <a href="https://stackoverflow.com/questions/280597/problem-with-date-daymonth-reversing-on-save">Problem with date day/month reversing on save</a></p>
<p>I have further noted that even setting the Session.LCID on the page itself is making no difference what so ever.</p>
<p>How could the environments be such that between test and live the asp site on live is reversing dates entered via SQL but not on test.</p>
<p>Both have the IUSR set to UK, both have all users set to UK, both have the SQL Account set to US English and both have Session.LCID set to 3081 (Australian English)</p>
<p>Why is test running " insert into datecolumn values '01/03/2008' and inserting '01/03/2008' and live is inserting '03/01/2008' "</p>
<p>The setups look totally identical. This must be figured out soon i'm getting quite scared that we'll never know. The problem is we may not change code or anything else. All I can do is investigate and tell them the cause. But I can't find it!</p>
<p>It's VB6/ASP and it's driving me do lally.</p>
<p>Access to the database is via a System DSN configured to use the correct SQL account.</p>
<p>What other info might you need.</p>
|
[
{
"answer_id": 284028,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 2,
"selected": true,
"text": "sp_configure 'default language' sysconfigures"
},
{
"answer_id": 284554,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 0,
"selected": false,
"text": "Format(YourDateVariable, \"yyyymmdd hh:nn:ss\")\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27412/"
] |
283,816
|
<p>I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package. </p>
<p>My question is: <strong>Is there a way to access this object in the default-package from a Java-class in a named package?</strong></p>
|
[
{
"answer_id": 283828,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": true,
"text": "import Unfinished;\n TypeName"
},
{
"answer_id": 284047,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "Groovy grails-app com.foo.<app>.<package> Convention"
},
{
"answer_id": 561183,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "Class fooClass = Class.forName(\"FooBar\");\nMethod fooMethod = fooClass.getMethod(\"fooMethod\", String.class);\n\nString fooReturned = (String)fooMethod.invoke(fooClass.newInstance(), \"I did it\");\n"
},
{
"answer_id": 22368012,
"author": "Sean",
"author_id": 3127264,
"author_profile": "https://Stackoverflow.com/users/3127264",
"pm_score": 3,
"selected": false,
"text": "rule * <target package name>.@1\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
283,821
|
<p>Does anyone know if there is an implementation of <code>javax.jms.QueueConnectionFactory</code> for WebSphere MQ and where to get it? I Googled it and searched IBM website but couldn't find anything. I don't want to retrieve the connection or factory from Websphere MQ via JNDI, I need my own connection factory.</p>
|
[
{
"answer_id": 283839,
"author": "Stroboskop",
"author_id": 23428,
"author_profile": "https://Stackoverflow.com/users/23428",
"pm_score": 4,
"selected": true,
"text": "com.ibm.mq.jar\ncom.ibm.mqbind.jar\ncom.ibm.mqjms.jar\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688/"
] |
283,824
|
<p>I can't figure out why the following wont work, any ideas??
public interface IFieldSimpleItem
{ }</p>
<pre><code>public interface IFieldNormalItem : IFieldSimpleItem
{ }
public class Person
{
public virtual T Create<T>()
where T : IFieldSimpleItem
{
return default(T);
}
}
public class Bose : Person
{
public override T Create<T>()
where T : IFieldNormalItem //This is where the error is
{
return default(T);
}
}
</code></pre>
<p>The reason why I am doing this is due to the fact that if a developer inherits from Bose, Bose relies on the instance being creating being at least of IFieldNormalItem. Whereas the below only relies on it being IFieldSimpleItem but the above should force it to be at least IFieldNormalItem.</p>
<pre><code>public class Person
{
public virtual IFieldSimpleItem Create()
{
return null;
}
}
public class Bose : Person
{
public override IFieldSimpleItem Create()
{
return null;
}
}
</code></pre>
<p>Cheers
Anthony</p>
|
[
{
"answer_id": 283837,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 1,
"selected": false,
"text": "public class Bose : Person\n{\n public virtual T CreateNormal<T>()\n where T : IFieldNormalItem //This is where the error is\n {\n return default(T);\n } \n}\n"
},
{
"answer_id": 283848,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "public interface IFieldNormalItem : IFieldSimpleItem\n{ }\n\npublic class Person<T> where T : IFieldSimpleItem\n{\n public virtual T Create()\n {\n return default(T);\n }\n}\n Person<IFieldSimpleItem> Person Person<IFieldNormalItem> Bose"
},
{
"answer_id": 283850,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 0,
"selected": false,
"text": "public class Bose : Person\n{\n public override T Create<T>()\n // where T : IFieldNormalItem // You don't need this line.\n {\n return default(T);\n } \n}\n public class Bose : Person\n{\n public virtual T Create<T>()\n where T : IFieldNormalItem\n {\n return default(T);\n } \n}\n"
},
{
"answer_id": 283862,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "public class Person<T> where T : IFieldSimpleItem\n{\n public virtual T Create()\n {\n return default(T);\n }\n}\n\npublic class Bose<T> : Person<T> where T : IFieldNormalItem\n{\n public override T Create()\n {\n return default(T);\n } \n}\n"
},
{
"answer_id": 283886,
"author": "Brent Rockwood",
"author_id": 31253,
"author_profile": "https://Stackoverflow.com/users/31253",
"pm_score": 0,
"selected": false,
"text": "Person[] people;\n[...initialize this somewhere...]\n\nforeach(Person p in people)\n p.Create<IFieldSimpleItem>();\n"
},
{
"answer_id": 286288,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 3,
"selected": true,
"text": "CheckCreatedType public class A\n{\n public IFieldSimpleItem Create()\n {\n IFieldSimpleItem created = InternalCreate();\n CheckCreatedType(created);\n return created;\n }\n\n protected virtual IFieldSimpleItem InternalCreate()\n {\n return new SimpleImpl();\n }\n protected virtual void CheckCreatedType(IFieldSimpleItem item)\n { \n // base class doesn't care. compiler guarantees IFieldSimpleItem\n }\n}\npublic class B : A\n{\n protected override IFieldSimpleItem InternalCreate()\n {\n // does not call base class.\n return new NormalImpl();\n }\n protected override void CheckCreatedType(IFieldSimpleItem item)\n {\n base.CheckCreatedType(item);\n if (!(item is IFieldNormalItem))\n throw new Exception(\"I need a normal item.\");\n\n }\n}\n base.CheckCreatedType(item) public class A\n{\n public IFieldSimpleItem Create()\n {\n IFieldSimpleItem created = InternalCreate();\n CheckCreatedType(created);\n return created;\n }\n\n protected virtual IFieldSimpleItem InternalCreate()\n {\n return new SimpleImpl();\n }\n\n private void CheckCreatedType(IFieldSimpleItem item)\n {\n Type inspect = this.GetType();\n bool keepgoing = true;\n while (keepgoing)\n {\n string name = inspect.FullName;\n if (CheckDelegateMethods.ContainsKey(name))\n {\n var checkDelegate = CheckDelegateMethods[name];\n if (!checkDelegate(item))\n throw new Exception(\"failed check\");\n }\n if (inspect == typeof(A))\n {\n keepgoing = false;\n }\n else\n {\n inspect = inspect.BaseType;\n }\n }\n }\n\n private static Dictionary<string,Func<IFieldSimpleItem,bool>> CheckDelegateMethods = new Dictionary<string,Func<IFieldSimpleItem,bool>>();\n protected static void RegisterCheckOnType(string name, Func<IFieldSimpleItem,bool> checkMethod )\n {\n CheckDelegateMethods.Add(name, checkMethod);\n }\n}\npublic class B : A\n{\n static B()\n {\n RegisterCheckOnType(typeof(B).FullName, o => o is IFieldNormalItem);\n }\n\n protected override IFieldSimpleItem InternalCreate()\n {\n // does not call base class.\n return new NormalImpl();\n }\n}\n System.Diagnostics.Conditional(\"DEBUG\")] Register.."
},
{
"answer_id": 286348,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 1,
"selected": false,
"text": "public interface IFieldSimpleItem { }\n\npublic interface IFieldNormalItem : IFieldSimpleItem{ }\n\npublic interface IFieldCreator<TField, TPerson> where TField : IFieldSimpleItem where TPerson : Person\n{\n TField Create(TPerson person);\n}\n\npublic class Person\n{\n}\n\npublic class Bose : Person\n{\n}\n\npublic class PersonFieldCreator : IFieldCreator<IFieldSimpleItem, Person> \n{\n public IFieldSimpleItem Create(Person person) { return null; }\n}\n\npublic class BoseFieldCreator : IFieldCreator<IFieldNormalItem, Bose>\n{\n public IFieldNormalItem Create(Bose person) { return null; }\n}\n"
},
{
"answer_id": 286789,
"author": "Buu",
"author_id": 17815,
"author_profile": "https://Stackoverflow.com/users/17815",
"pm_score": 2,
"selected": false,
"text": "public interface IFieldSuperItem : IFieldSimpleItem\n Person p = new Boss();\np.Create<IFieldSuperItem>();\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30572/"
] |
283,835
|
<p>I am trying to establish a basic .NET Remoting communication between 2x 64bit windows machines. If Machine1 is acting as client and Machine2 as server, then everything works fine. The other way around the following exception occurs:</p>
<p>System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 172.16.7.44:6666</p>
<p>The server code:</p>
<pre><code>TcpChannel channel = new TcpChannel(6666);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(MyRemotableObject),"HelloWorld",WellKnownObjectMode.Singleton);
</code></pre>
<p>The client code:</p>
<pre><code>TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
// Create an instance of the remote object
remoteObject = (MyRemotableObject)Activator.GetObject(
typeof(MyRemotableObject), "tcp://172.16.7.44:6666/HelloWorld");
</code></pre>
<p>Any idea whats wrong with my code?</p>
|
[
{
"answer_id": 283843,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": false,
"text": "netstat -an"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35061/"
] |
283,858
|
<p>I have an XML input file and I'm trying to output the result of a call like: </p>
<pre><code><xsl:value-of select="Some/Value"/>
</code></pre>
<p>into an attribute. </p>
<pre><code><Output Attribute="Value should be put here"/>
</code></pre>
<p>My problem is, since I'm outputting XML, the XSL processor won't allow me to write: </p>
<pre><code><Output Attribute="<xsl:value-of select="Some/Value"/>">
</code></pre>
<p>How do you accomplish this?</p>
|
[
{
"answer_id": 283868,
"author": "Phil Ross",
"author_id": 5981,
"author_profile": "https://Stackoverflow.com/users/5981",
"pm_score": 5,
"selected": false,
"text": "<Output>\n <xsl:attribute name=\"Attribute\">\n <xsl:value-of select=\"Some/Value\"/>\n </xsl:attribute>\n</Output>\n"
},
{
"answer_id": 283877,
"author": "Danko Durbić",
"author_id": 19241,
"author_profile": "https://Stackoverflow.com/users/19241",
"pm_score": 7,
"selected": true,
"text": "<Output Attribute=\"{Some/Value}\"/>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
] |
283,869
|
<p>I'm trying to add a new node to an jQuery <a href="http://news.kg/wp-content/uploads/tree/" rel="nofollow noreferrer">SimpleTree</a>, but all I seem to be able to get is "sTC.addNode is not a function"... </p>
<pre><code>var simpleTreeCollection = $('.simpleTree').simpleTree({
animate:true,
drag:false,
autoclose: false,
afterClick:function(node){},
afterDblClick:function(node){},
beforeMove:function (destination, source, pos){},
afterMove:function(destination, source, pos){},
afterAjax:function() {},
afterContextMenu:function(node){}
});
simpleTreeCollection.addNode('test', 'test');
</code></pre>
<p>Any suggestions what I might be doing wrong? Is there even the possibility to add a node?</p>
|
[
{
"answer_id": 283914,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 1,
"selected": false,
"text": " //Select first child node in tree\n $('#2').click();\n //Add new node to selected node\n simpleTreeCollection.get(0).addNode(1,'A New Node')\n"
},
{
"answer_id": 970974,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " TREE.addNode = function(id, text, callback)\n {\n var temp_node = $('<li><ul><li id=\"'+id+'\"><span>'+text+'</span></li></ul></li>');\n TREE.setTreeNodes(temp_node);\n dragNode_destination = TREE.getSelected();\n dragNode_source = $('.doc-last',temp_node);\n TREE.moveNodeToFolder(dragNode_destination);\n// temp_node.remove();\n dragNode_destination.after(dragNode_source);\n if(typeof(callback) == 'function')\n {\n callback(dragNode_destination, dragNode_source);\n }\n };\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999/"
] |
283,888
|
<p>what's the best/proper way of interacting between several windows in C# app?
Recently, I've run into a problem where one of program windows has to call method modifying main window. My solution was to create factory-like class, that would arrange all underlying model-data and organize the communication between various windows (through delegates). However, as passing one or two delegates was not a problem, I started thinking what if my other windows would need 10 delegates to interact properly with main window? Are delegates good solution? How to pass them in good way - through constructor, properties? Or maybe the need of using that many delegates is some serious design flaw itself?</p>
|
[
{
"answer_id": 283933,
"author": "Sekhat",
"author_id": 1610,
"author_profile": "https://Stackoverflow.com/users/1610",
"pm_score": 0,
"selected": false,
"text": "public class MainForm : Form\n{\n}\n\npublic class OtherForm : Form\n{\n protected MainForm MainForm { get; set; }\n\n public OtherForm(MainForm mainForm) : base()\n {\n this.MainForm = mainForm;\n }\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36890/"
] |
283,891
|
<p>How can I access the WCF Service through JavaScript?
My problem is, I have to access the operation contracts through the JavaScript (my website is not Ajax enabled).<br>
Previously for calling .asmx web services,
I am using the following code snippet</p>
<pre><code>var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttp.open("POST", URL, false);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(payload);
xmlData = xmlHttp.responseXML;
</code></pre>
<p>where url is my webservice location.</p>
<p>Now if I am trying to consume the wcf service in the same manner, I am not able to.
Many techies are explaining through AJAX approach,
I need an approach without AJAX.</p>
|
[
{
"answer_id": 284409,
"author": "user32415",
"author_id": 32415,
"author_profile": "https://Stackoverflow.com/users/32415",
"pm_score": 0,
"selected": false,
"text": "[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]\n \"Content-Type\", \"application/x-www-form-urlencoded\"\n \"Content-Type\", \"application/json\"\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,893
|
<p>To support multiple platforms in C/C++, one would use the preprocessor to enable conditional compiles. E.g.,</p>
<pre><code>#ifdef _WIN32
#include <windows.h>
#endif
</code></pre>
<p>How can you do this in Ada? Does Ada have a preprocessor?</p>
|
[
{
"answer_id": 8264429,
"author": "Rego",
"author_id": 1005540,
"author_profile": "https://Stackoverflow.com/users/1005540",
"pm_score": 2,
"selected": false,
"text": "gnatprep #if SOMESWITCH then\n-- Your code here is executed only if the switch SOMESWITCH is active in your build configuration\n#end if;\n gnatmake gprbuild gnatprep"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
] |
283,894
|
<p>Have you ever tried this feedback calling an external zip.py script to work? My CGITB does not show any error messages. It simply did not invoke external .py script to work. It simply skipped over to gush. I should be grateful if you can assist me in making this zip.py callable in feedback.py. </p>
<p>Regards. David </p>
<pre><code>#**********************************************************************
# Description:
# Zips the contents of a folder.
# Parameters:
# 0 - Input folder.
# 1 - Output zip file. It is assumed that the user added the .zip
# extension.
#**********************************************************************
# Import modules and create the geoprocessor
#
import sys, zipfile, arcgisscripting, os, traceback
gp = arcgisscripting.create()
# Function for zipping files. If keep is true, the folder, along with
# all its contents, will be written to the zip file. If false, only
# the contents of the input folder will be written to the zip file -
# the input folder name will not appear in the zip file.
#
def zipws(path, zip, keep):
path = os.path.normpath(path)
# os.walk visits every subdirectory, returning a 3-tuple
# of directory name, subdirectories in it, and filenames
# in it.
#
for (dirpath, dirnames, filenames) in os.walk(path):
# Iterate over every filename
#
for file in filenames:
# Ignore .lock files
#
if not file.endswith('.lock'):
gp.AddMessage("Adding %s..." % os.path.join(path, dirpath, file))
try:
if keep:
zip.write(os.path.join(dirpath, file),
os.path.join(os.path.basename(path),
os.path.join(dirpath, file)[len(path)+len(os.sep):]))
else:
zip.write(os.path.join(dirpath, file),
os.path.join(dirpath[len(path):], file))
except Exception, e:
gp.AddWarning(" Error adding %s: %s" % (file, e))
return None
if __name__ == '__main__':
try:
# Get the tool parameter values
#
infolder = gp.GetParameterAsText(0)
outfile = gp.GetParameterAsText(1)
# Create the zip file for writing compressed data. In some rare
# instances, the ZIP_DEFLATED constant may be unavailable and
# the ZIP_STORED constant is used instead. When ZIP_STORED is
# used, the zip file does not contain compressed data, resulting
# in large zip files.
#
try:
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
zipws(infolder, zip, True)
zip.close()
except RuntimeError:
# Delete zip file if exists
#
if os.path.exists(outfile):
os.unlink(outfile)
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED)
zipws(infolder, zip, True)
zip.close()
gp.AddWarning(" Unable to compress zip file contents.")
gp.AddMessage("Zip file created successfully")
except:
# Return any python specific errors as well as any errors from the geoprocessor
#
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo +
"\nError Info:\n " + str(sys.exc_type) +
": " + str(sys.exc_value) + "\n"
gp.AddError(pymsg)
msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n"
gp.AddError(msgs)
</code></pre>
|
[
{
"answer_id": 284199,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "zip() zip zip_ execfile() import zip_ execfile()"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36900/"
] |
283,925
|
<p>Ok so I have an abstract base class called Product, a KitItem class that inherits Product and a PackageKitItem class that inherits KitItem. ie.</p>
<pre><code>Product
KitItem : Product
PackageKitItem : KitItem
</code></pre>
<p>I have my KitItems loaded and I need to load up a collection of PackageKitItems which are, effectively, shallow copies of KitItems.</p>
<p>Currently we are doing what feels to me a hacky shallow copy in the Product constructor like so:</p>
<pre><code>public Product(Product product)
{
FieldInfo[] fields = product.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
// copy each value over to 'this'
foreach (FieldInfo fi in fields)
fi.SetValue(this, fi.GetValue(product));
}
</code></pre>
<p>I've tried setting up a copy on KitItem like so:</p>
<pre><code>public KitItem ShallowCopy()
{
return (KitItem)this.MemberwiseClone();
}
</code></pre>
<p>and calling it thus:</p>
<pre><code>PackageKitItem tempPackKitItem = (PackageKitItem)packKitItem.ShallowCopy();
</code></pre>
<p>but I get an invalid cast. I'm looking for ideas for the best way to accomplish this.</p>
|
[
{
"answer_id": 284021,
"author": "Leonardo Herrera",
"author_id": 7841,
"author_profile": "https://Stackoverflow.com/users/7841",
"pm_score": 0,
"selected": false,
"text": "PackageKitItem tempPackKitItem = new tempPackKitItem(kitItem);\n"
},
{
"answer_id": 284034,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Reflection;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n PackageKitItem PKI = new PackageKitItem();\n PKI.ID = 1;\n PKI.KitName = \"2\";\n PKI.Name = \"3\";\n PKI.Package = 4;\n\n PackageKitItem tempPackKitItem = (PackageKitItem)PKI.ShallowCopy();\n\n }\n }\n\n}\n\npublic class Product\n{\n public int ID;\n public string Name;\n\n public Product()\n {\n }\n\n public Product(Product product)\n {\n FieldInfo[] fields = product.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);\n\n // copy each value over to 'this'\n foreach (FieldInfo fi in fields)\n fi.SetValue(this, fi.GetValue(product));\n }\n\n\n}\n\npublic class KitItem:Product\n{\n public string KitName;\n public KitItem ShallowCopy()\n {\n return (KitItem)this.MemberwiseClone();\n }\n\n}\n\npublic class PackageKitItem : KitItem\n{\n public int Package;\n\n}\n"
},
{
"answer_id": 292973,
"author": "TAG",
"author_id": 36400,
"author_profile": "https://Stackoverflow.com/users/36400",
"pm_score": 3,
"selected": true,
"text": "public virtual KitItem ShallowCopy() \n{ \n return (KitItem) this.MemberwiseClone(); \n}\n public override KitItem ShallowCopy() \n{ \n return (PackageKitItem) this.MemberwiseClone(); \n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12862/"
] |
283,931
|
<p>Could somebody please explain to me what happens here?<br>
I am creating a binding in code. </p>
<p>The target object is a UserControl<br>
The target property is a boolean DependencyProperty<br>
The source object is a FrameworkElement and implements INotifyPropertyChanged<br>
The source property is of type ObservableCollection </p>
<p>What happens:</p>
<ul>
<li><p>The binding is created in code, the result BindingExpressionBase looks fine, the mode is OneWay, the target value gets set correctly (at this time)</p>
<p>Binding b = new Binding();<br>
b.Path = "SourceProperty";<br>
b.Source = SourceObject;<br>
BindingExpressionBase e = this.SetBinding(TargetProperty, b); </p></li>
<li><p>The source property then gets changed as a result of another databinding. The UserControl tries to fire the PropertyChanged event.</p></li>
<li><p>....but nobody is listening. PropertyChanged is null.</p></li>
</ul>
<p>I am sure that nothing else is assigned to the target property, so it should still be bound. Why is the binding not listening for the PropertyChanged event?</p>
|
[
{
"answer_id": 284303,
"author": "jarda",
"author_id": 6601,
"author_profile": "https://Stackoverflow.com/users/6601",
"pm_score": 3,
"selected": true,
"text": "if (PropertyChanged != null) \n{ \n PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); \n} \n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6601/"
] |
283,942
|
<p>I have a TObjectList with OwnsObjects = true. It contains quite a few objects. Now I want to remove the object at index Idx from that list, without freeing it.</p>
<p>Is the Extract method the only option?</p>
<p><code>ExtractedObject := TheList.Extract(TheList[Idx]);</code></p>
<p>All other methods seem to free the object. I am looking for something a little bit more efficient, that does not do a linear search every time, since I already know the index of the object. Something like an overloaded ...</p>
<p><code>ExtractedObject := TheList.Extract(Idx);</code></p>
<p>... which does not exist.</p>
|
[
{
"answer_id": 284162,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 1,
"selected": false,
"text": " TMyObjectList = Class(TObjectList)\n private\n fNotify: Boolean;\n { Private declarations }\n procedure EnableNotification;\n procedure DisableNotification;\n protected\n procedure Notify(Ptr: Pointer; Action: TListNotification); override;\n public\n constructor Create(AOwnsObjects: Boolean);overload;\n constructor Create; overload;\n function Extract(const idx : Integer) : TObject;\n end;\n\n\nconstructor TMyObjectList.Create(AOwnsObjects: Boolean);\nbegin\n inherited Create(AOwnsObjects);\n fNotify := True;\nend;\n\nconstructor TMyObjectList.Create;\nbegin\n inherited Create;\n fNotify := True;\nend;\n\nprocedure TMyObjectList.DisableNotification;\nbegin\n fnotify := False;\nend;\n\nprocedure TMyObjectList.EnableNotification;\nbegin\n fNotify := True;\nend;\n\nfunction TMyObjectList.Extract(const idx: Integer) : TObject;\nbegin\n Result := Items[idx];\n DisableNotification;\n try\n Delete(idx);\n finally\n EnableNotification;\n end;\nend;\n\nprocedure TMyObjectList.Notify(Ptr: Pointer; Action: TListNotification);\nbegin\n if fNotify then\n inherited;\nend;\n"
},
{
"answer_id": 284244,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 1,
"selected": false,
"text": "TObjectListHelper = class helper for TObjectList\n function ExtractByIndex(const AIndex: Integer): TObject;\nend;\n\nfunction TObjectListHelper.ExtractByIndex(const AIndex: Integer): TObject;\nbegin\n Result := Items[AIndex];\n if Result<>nil then\n Extract(Result);\nend;\n MyObjList.ExtractByIndex(MyIndex);\n"
},
{
"answer_id": 285384,
"author": "Vegar",
"author_id": 11956,
"author_profile": "https://Stackoverflow.com/users/11956",
"pm_score": 1,
"selected": false,
"text": "obj := list[idx];\nlist.list^[idx] := nil; //<- changed from list[idx] := nil;\nlist.delete(idx);\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21506/"
] |
283,943
|
<p>I have a list of strings displayed by a Silverlight ItemsControl. The DataTemplate is a Border control with a TextBlock as its child. How can I access the border control corresponding to an item? For example, I might want to do this to change the background color.</p>
|
[
{
"answer_id": 285017,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 2,
"selected": false,
"text": "<Grid>\n <ItemsControl x:Name=\"items\">\n <ItemsControl.ItemTemplate>\n <DataTemplate>\n <Border>\n <TextBlock MouseEnter=\"TextBlock_MouseEnter\" MouseLeave=\"TextBlock_MouseLeave\" Text=\"{Binding}\" />\n </Border>\n </DataTemplate>\n </ItemsControl.ItemTemplate>\n </ItemsControl>\n</Grid>\n public Page()\n{\n InitializeComponent();\n\n items.ItemsSource = new string[] { \"This\", \"Is\", \"A\", \"Test\" };\n}\n\nprivate void TextBlock_MouseEnter(object sender, MouseEventArgs e)\n{\n var tx = sender as TextBlock;\n var bd = tx.Parent as Border;\n bd.Background = new SolidColorBrush(Colors.Yellow);\n}\n\nprivate void TextBlock_MouseLeave(object sender, MouseEventArgs e)\n{\n var tx = sender as TextBlock;\n var bd = tx.Parent as Border;\n bd.Background = new SolidColorBrush(Colors.White);\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
283,950
|
<p>When looking at C# code, I often see patterns like this:</p>
<pre><code>DataType[] items = GetSomeItems();
OtherDataType[] itemProps = new OtherDataType[items.Length];
int i = 0;
foreach (DataType item in items)
{
// Do some stuff with item, then finally
itemProps[i] = item.Prop;
i++;
}
</code></pre>
<p>The for-loop iterates over the objects in <code>items</code>, but also keeping a counter (<code>i</code>) for iterating over <code>itemProps</code> as well. I personally don't like this extra <code>i</code> hanging around, and instead would probably do something like:</p>
<pre><code>DataType[] items = GetSomeItems();
OtherDataType[] itemProps = new OtherDataType[items.Length];
for (int i = 0; i < items.Length; i++)
{
// Do some stuff with items[i], then finally
itemProps[i] = items[i].Prop;
}
</code></pre>
<p>Is there perhaps some benfit to the first approach I'm not aware of? Is this a result of everybody trying to use that fancy <code>foreach (...)</code> syntax? I'm interested in your opinions on this.</p>
|
[
{
"answer_id": 283966,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "this[int index]"
},
{
"answer_id": 283971,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 3,
"selected": false,
"text": "OtherDataType[] itemProps = items.Select(i=>i.Prop).ToArray();\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/283950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2576/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.