instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>How would you go about creating a random alpha-numeric string that matches a certain regular expression?</p>
<p>This is specifically for creating initial passwords that fulfill regular password requirements.</p>
|
<p>Welp, just musing, but the general question of generating random inputs that match a regex sounds doable to me for a sufficiently relaxed definition of random and a sufficiently tight definition of regex. I'm thinking of the classical formal definition, which allows only ()|* and alphabet characters. </p>
<p>Regular expressions can be mapped to formal machines called <a href="http://en.wikipedia.org/wiki/Deterministic_finite_automata" rel="noreferrer">finite automata</a>. Such a machine is a directed graph with a particular node called the final state, a node called the initial state, and a letter from the alphabet on each edge. A word is accepted by the regex if it's possible to start at the initial state and traverse one edge labeled with each character through the graph and end at the final state.</p>
<p>One could build the graph, then start at the final state and traverse random edges backwards, keeping track of the path. In a standard construction, every node in the graph is reachable from the initial state, so you do not need to worry about making irrecoverable mistakes and needing to backtrack. If you reach the initial state, stop, and read off the path going forward. That's your match for the regex.</p>
<p>There's no particular guarantee about when or if you'll reach the initial state, though. One would have to figure out in what sense the generated strings are 'random', and in what sense you are hoping for a random element from the language in the first place.</p>
<p>Maybe that's a starting point for thinking about the problem, though!</p>
<p>Now that I've written that out, it seems to me that it might be simpler to repeatedly resolve choices to simplify the regex pattern until you're left with a simple string. Find the first non-alphabet character in the pattern. If it's a *, replicate the preceding item some number of times and remove the *. If it's a |, choose which of the OR'd items to preserve and remove the rest. For a left paren, do the same, but looking at the character following the matching right paren. This is probably easier if you parse the regex into a tree representation first that makes the paren grouping structure easier to work with.</p>
<p>To the person who worried that deciding if a regex actually matches anything is equivalent to the halting problem: Nope, regular languages are quite well behaved. You can tell if any two regexes describe the same set of accepted strings. You basically make the machine above, then follow an algorithm to produce a canonical minimal equivalent machine. Do that for two regexes, then check if the resulting minimal machines are equivalent, which is straightforward. </p>
|
<p>Presuming you have both a minimum length and 3-of-4* (or similar) requirement, I'd just be inclined to use a decent password generator.</p>
<p>I've built a couple in the past (both web-based and command-line), and have never had to skip more than one generated string to pass the 3-of-4 rule.</p>
<ul>
<li>3-of-4: must have at least three of the following characteristics: lowercase, uppercase, number, symbol</li>
</ul>
| 25,166
|
<p>Here's a link to Windows <a href="http://msdn.microsoft.com/en-us/library/ms683218(VS.85).aspx" rel="nofollow noreferrer">documentation</a>.</p>
<p>Basically I would like to get similar data, but on Linux. If not all is possible, then at least some parts.</p>
|
<p>If you enable <code>CONFIG\_TASK\_IO\_ACCOUNTING</code>, you will have the information available in /proc/<pid>/io. This is available since kernel 2.6.20, but not normally enabled by default (However, in Ubuntu 8.04 it seems like it is enabled).</p>
<p>You can read about the various data items in <a href="http://lxr.linux.no/linux+v2.6.26.5/Documentation/filesystems/proc.txt" rel="nofollow noreferrer">Documentation/filesystems/proc.txt</a> in the kernel source tree. Especially section <a href="http://lxr.linux.no/linux+v2.6.26.5/Documentation/filesystems/proc.txt#L2226" rel="nofollow noreferrer">2.14</a> should be of interest.</p>
|
<p>Look at the pseudo-files under <code>/proc/<PID>/</code>. Maybe you can find what you need there.</p>
<hr>
<p>Look at <code>man 5 proc</code>, or failing that the kernel documentation. However, I don't see much that looks promising. Sorry.</p>
| 20,302
|
<p>I am creating an ZIP file with <code>ZipFile</code> in Python 2.5, it works OK so far:</p>
<pre><code>import zipfile, os
locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()
</code></pre>
<p>But I couldn't find how to encrypt the files in the ZIP file.
I could use system and call <code>PKZIP -s</code>, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.</p>
|
<p>I created a simple library to create a password encrypted zip file in python. - <a href="https://github.com/smihica/pyminizip" rel="noreferrer"><strong>here</strong></a></p>
<pre><code>import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("src.txt", "dst.zip", "password", compression_level)
</code></pre>
<p><strong>The library requires zlib.</strong></p>
<p>I have checked that the file can be extracted in WINDOWS/MAC.</p>
|
<p>You can use the <a href="http://www.chilkatsoft.com/python.asp" rel="nofollow noreferrer">Chilkat</a> library. It's commercial, but has a free evaluation and seems pretty nice.</p>
<p>Here's an example I got from <a href="http://www.example-code.com/python/zip.asp" rel="nofollow noreferrer">here</a>:</p>
<pre><code>import chilkat
# Demonstrates how to create a WinZip-compatible 128-bit AES strong encrypted zip
zip = chilkat.CkZip()
zip.UnlockComponent("anything for 30-day trial")
zip.NewZip("strongEncrypted.zip")
# Set the Encryption property = 4, which indicates WinZip compatible AES encryption.
zip.put_Encryption(4)
# The key length can be 128, 192, or 256.
zip.put_EncryptKeyLength(128)
zip.SetPassword("secret")
zip.AppendFiles("exampleData/*",True)
zip.WriteZip()
</code></pre>
| 3,794
|
<p>In a previous question, I asked about various ORM libraries. It turns out Kohana looks very clean yet functional for the purposes of ORM. I already have an MVC framework that I am working in though. If I don't want to run it as a framework, what is the right fileset to include to just give me the DB and ORM base class files?</p>
<p>Update:</p>
<p>I jumped in and started looking at the ORM source code.. One thing was immediately confusing to me.. all the ORM classes have the class name appended with _CORE i.e. ORM_Core ORM_Iterator_Core, but the code everywhere is extending the ORM class. Problem is, I've searched the whole code base 6 different ways, and I've never seen a plain ORM class def nor an ORM interface def or anything.. Could someone enlighten me on where that magic happens?</p>
|
<p>Why not just have a </p>
<pre><code>class ORM extends ORM_Core {}
</code></pre>
<p>somewhere in your code? This removes the need to use any of the loader code.</p>
<p>You'll also need Kohana_Exception, the Database library (and appropraite driver), Kohana::config(), Kohana::auto_load(), Kohana::log() methods (search Database.php for those). </p>
<p>Kohana is a great MVC framework, but not really designed to be taken apart in chunks like that. You may want to also investigate <a href="http://www.doctrine-project.org/" rel="noreferrer">Doctrine</a>, another ORM for PHP (that IS designed to be stand-alone)</p>
|
<p><a href="http://obando.com.ve/2009/04/29/modelado-orm-rapido-y-facil/" rel="nofollow noreferrer">http://obando.com.ve/2009/04/29/modelado-orm-rapido-y-facil/</a></p>
<p>That is all your need!! </p>
| 27,637
|
<p>I would like to add a method to a built-in type (e.g. Double), so that I can use an <code>infix</code> operator. Is that possible?</p>
|
<p>Yes and no. Yes, you can make it <em>seem</em> like you have added a method to <code>double</code>. For example:</p>
<pre><code>class MyRichDouble(d: Double) {
def <>(other: Double) = d != other
}
implicit def doubleToSyntax(d: Double) = new MyRichDouble(d)
</code></pre>
<p>This code adds the previously-unavailable <code><></code> operator to any object of type <code>Double</code>. So long as the <code>doubleToSyntax</code> method is in scope so that it could be invoked without qualification, the following will work:</p>
<pre><code>3.1415 <> 2.68 // => true
</code></pre>
<p>The "no" part of the answer comes from the fact that you aren't really adding anything to the <code>Double</code> class. Instead, you are creating a conversion from <code>Double</code> to a new type which does define the method you want. This can be a much more powerful technique than the open-classes offered by many dynamic languages. It also happens to be completely type-safe. :-)</p>
<p>Some limitations you should be aware of:</p>
<ul>
<li>This technique does not allow you to <em>remove</em> or <em>redefine</em> existing methods, just add new ones</li>
<li>The implicit conversion method (in this case, <code>doubleToSyntax</code>) absolutely must be in-scope for the desired extension method to be available</li>
</ul>
<p>Idiomatically, implicit conversions are either placed within singleton objects and imported (e.g. <code>import Predef._</code>) or within traits and inherited (e.g. <code>class MyStuff extends PredefTrait</code>).</p>
<p>Slight aside: "infix operators" in Scala are actually methods. There is no magic associated with the <code><></code> method which allows it to be infix, the parser simply accepts it that way. You can also use "regular methods" as infix operators if you like. For example, the <code>Stream</code> class defines a <code>take</code> method which takes a single <code>Int</code> parameter and returns a new <code>Stream</code>. This can be used in the following way:</p>
<pre><code>val str: Stream[Int] = ...
val subStream = str take 5
</code></pre>
<p>The <code>str take 5</code> expression is literally identical to <code>str.take(5)</code>.</p>
|
<p>This feature came in handy to implement a class performing error estimation:</p>
<pre><code>object errorEstimation {
class Estimate(val x: Double, val e: Double) {
def + (that: Estimate) =
new Estimate(this.x + that.x, this.e + that.e)
def - (that: Estimate) =
new Estimate(this.x - that.x, this.e + that.e)
def * (that: Estimate) =
new Estimate(this.x * that.x,
this.x.abs*that.e+that.x.abs*this.e+this.e*that.e)
def / (that: Estimate) =
new Estimate(this.x/that.x,
(this.x.abs*that.e+that.x.abs*this.e)/(that.x.abs*(that.x.abs-that.e)))
def +- (e2: Double) =
new Estimate(x,e+e2)
override def toString =
x + " +- " + e
}
implicit def double2estimate(x: Double): Estimate = new Estimate(x,0)
implicit def int2estimate(x: Int): Estimate = new Estimate(x,0)
def main(args: Array[String]) = {
println(((x: Estimate) => x+2*x+3*x*x)(1 +- 0.1))
// 6.0 +- 0.93
println(((x: Estimate) => (((y: Estimate) => y*y + 2)(x+x)))(1 +- 0.1))
// 6.0 +- 0.84
def poly(x: Estimate) = x+2*x+3/(x*x)
println(poly(3.0 +- 0.1))
// 9.33333 +- 0.3242352
println(poly(30271.3 +- 0.0001))
// 90813.9 +- 0.0003
println(((x: Estimate) => poly(x*x))(3 +- 1.0))
// 27.037 +- 20.931
}
}
</code></pre>
| 38,151
|
<p>We have Core2 machines (Dell T5400) with XP64.</p>
<p>We observe that when running 32-bit processes,
the performance of memcpy is on the order of
1.2GByte/s; however memcpy in a 64-bit process
achieves about 2.2GByte/s (or 2.4GByte/s
with the Intel compiler CRT's memcpy). While the
initial reaction might be to just explain this
away as due to the wider registers available
in 64-bit code, we observe that our own memcpy-like
SSE assembly code (which should be using 128-bit
wide load-stores regardless of 32/64-bitness of
the process) demonstrates similar upper limits on
the copy bandwidth it achieves.</p>
<p>My question is, what's this difference actually
due to ? Do 32-bit processes have to jump through
some extra WOW64 hoops to get at the RAM ? Is it something
to do with TLBs or prefetchers or... what ?</p>
<p>Thanks for any insight.</p>
<p>Also raised on <a href="http://software.intel.com/en-us/forums/intel-avx-and-cpu-instructions/topic/63277/" rel="noreferrer">Intel forums</a>.</p>
|
<p>I think the following can explain it:</p>
<p>To copy data from memory to a register and back to memory, you do</p>
<pre><code>mov eax, [address]
mov [address2], eax
</code></pre>
<p>This moves 32 bit (4 byte) from address to address2. The same goes with 64 bit in 64 bit mode</p>
<pre><code>mov rax, [address]
mov [address2], rax
</code></pre>
<p>This moves 64 bit, 2 byte, from address to address2. "mov" itself, regardless of whether it is 64 bit or 32 bit has a latency of 0.5 and a throughput of 0.5 according to Intel's specs. Latency is how many clock cycles the instruction takes to travel through the pipeline and throughput is how long the CPU has to wait before accepting the same instruction again. As you can see, it can do two mov's per clock cycle, however, it has to wait half a clock cycle between two mov's, thus it can effectively only do one mov per clock cycle (or am I wrong here and misinterpret the terms? See <a href="http://www.intel.com/design/processor/manuals/248966.pdf" rel="nofollow noreferrer">PDF here</a> for details).</p>
<p>Of course a <code>mov reg, mem</code> can be longer than 0.5 cycles, depending if the data is in 1st or 2nd level cache, or not in cache at all and needs to be grabbed from memory. However, the latency time of above ignores this fact (as the PDF states I linked above), it assumes all data necessary for the mov are present already (otherwise the latency will increase by how long it takes to fetch the data from wherever it is right now - this might be several clock cycles and is completely independent of the command being executed says the PDF on page 482/C-30).</p>
<p>What is interesting, whether the mov is 32 or 64 bit plays no role. That means unless the memory bandwidth becomes the limiting factor, 64 bit mov's are equally fast to 32 bit mov's, and since it takes only half as many mov's to move the same amount of data from A to B when using 64 bit, the throughput can (in theory) be twice as high (the fact that it's not is probably because memory is not unlimited fast).</p>
<p>Okay, now you think when using the larger SSE registers, you should get faster throughput, right? AFAIK the xmm registers are not 256, but 128 bit wide, BTW (<a href="http://en.wikipedia.org/wiki/Streaming_SIMD_Extensions" rel="nofollow noreferrer">reference at Wikipedia</a>). However, have you considered latency and throughput? Either the data you want to move is 128 bit aligned or not. Depending on that, you either move it using</p>
<pre><code>movdqa xmm1, [address]
movdqa [address2], xmm1
</code></pre>
<p>or if not aligned</p>
<pre><code>movdqu xmm1, [address]
movdqu [address2], xmm1
</code></pre>
<p>Well, movdqa/movdqu has a latency of 1 and a throughput of 1. So the instructions take twice as long to be executed and the waiting time after the instructions is twice as long as a normal mov.</p>
<p>And something else we have not even taken into account is the fact that the CPU actually splits instructions into micro-ops and it can execute these in parallel. Now it starts getting really complicated... even too complicated for me.</p>
<p>Anyway, I know from experience loading data to/from xmm registers is much slower than loading data to/from normal registers, so your idea to speed up transfer by using xmm registers was doomed from the very first second. I'm actually surprised that in the end the SSE memmove is not much slower than the normal one.</p>
|
<p>I don't have a reference in front of me, so I'm not absolutely positive on the timings/instructions, but I can still give the theory. If you're doing a memory move under 32-bit mode, you'll do something like a "rep movsd" which moves a single 32-bit value every clock cycle. Under 64-bit mode, you can do a "rep movsq" which does a single 64-bit move every clock cycle. That instruction is not available to 32-bit code, so you'd be doing 2 x rep movsd (at 1 cycle a piece) for half the execution speed.</p>
<p>VERY much simplified, ignoring all the memory bandwidth/alignment issues, etc, but this is where it all begins...</p>
| 33,841
|
<p>I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links:</p>
<pre><code><A HREF="path to file">filename</A>
</code></pre>
<p>The filenames can be complicated:</p>
<pre><code>LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf
</code></pre>
<p>What is the correct way to link to this file on a Linux/Apache server?</p>
<p>Is there a PHP function to do this conversion?</p>
|
<p>You can use <a href="http://php.net/manual/en/function.rawurlencode.php" rel="nofollow noreferrer">rawurlencode()</a> to convert a string according to the RFC 1738 spec.
This function replaces all non-alphanumeric characters by their associated code.</p>
<p>The difference with <a href="http://php.net/manual/en/function.urlencode.php" rel="nofollow noreferrer">urlencode()</a> is that spaces are encoded as plus signs.</p>
<p>You'll probably want to use the last one.</p>
<p>This technique is called Percent or URL encoding. See <a href="http://en.wikipedia.org/wiki/Url_encoding" rel="nofollow noreferrer">Wikipedia</a> for more details.</p>
|
<p><a href="http://se.php.net/manual/en/function.urlencode.php" rel="nofollow noreferrer">urlencode()</a> should probably do what you want.</p>
<p><strong>Edit</strong>: urlencode() works fine on swedish characters.</p>
<pre><code>
<?php
echo urlencode("åäö");
?>
</code></pre>
<p>converts to:</p>
<pre><code>
%E5%E4%F6
</code></pre>
| 5,547
|
<p>When creating web parts for Sharepoint, is it better to create an actual web part, or is using and ASP.NET User Control (.ascx) just as good?</p>
<p>I already know how to create the user controls that I need, so it seems like the extra effort of creating a web part is just unnecessary leg work.</p>
<p>What are the advantages of using a web part over just creating and ASP.NET user control?</p>
|
<p>I am a big fan of user controls except for the simplest web parts. I create a webpart that instantiates and loads the user control. There are other tools out there that you can use to expose your user control, like smartpart, but I would suggest you wrap it up yourself, as it is a good learning experience. Once you have done it once, you basically have a template for any other webpart you want to create.</p>
<p>Good Luck!</p>
|
<p>A bare ASP.NET ascx control would have to be added to a custom layout page. This limits the utility of the control a little as it cannot be added "just anywhere".</p>
<p>Having a webpart gives the flexibility of the control being added to the site multiple times in different locations or even multiple times on the same page with different properties. </p>
<p>As has been mentioned it is good to use <code>CreateChildControls()</code> to create the controls in the webpart and it is not that much of a big deal to code and package a webpart into a solution, making it worth the extra effort.</p>
<p>Webparts are also able to accept connections from "filter" webparts on the same page, giving additional flexibility to webparts compared to hosting ascx controls on the site.</p>
<p>When it comes to editors using the site, it makes a lot of difference for them to be able to add a webpart compared to editing a page layout, publishing it and then creating pages based on that page layout, so from the perspective of a site editor, the difference in usability is really quite large.</p>
<p>I recommend going even further and coding your webpart to use an xslt file to display the contents and making the location of that xslt a configurable property of the webpart. This <em>really</em> adds to the flexibility of your control.</p>
<p>Look at the Dataview webpart to see how much can be done with the addition of custom rendering.</p>
| 28,679
|
<p>I have a layered application in Java which has a multi thread data access layer which is invoked from different points. A single call to this layer is likely to spawn several threads to parallelize requests to the DB. </p>
<p>What I'm looking for is a logging tool that would allow me to define "activities" that are composed by various threads. Therefore, the same method in the data access layer should log different outputs depending on its caller. The ability to group different outputs to summarize the total cost of an operation is also important.</p>
<p>Although the application is in Java, language is not a restriction; what I need are the design guidelines so to eventually implement it. We are currently using log4j, but can't get this behaviour from it.</p>
|
<p>You should also have a look at the <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html" rel="noreferrer">nested diagnostic context</a> feature of log4j. Pushing different contexts to the logger for different callers might do the trick for you.</p>
|
<p>In Java5 (and later) you can call </p>
<pre><code>StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
</code></pre>
<p>Inspect the stack trace to whatever depth you want and log accordingly.</p>
<p>In Java 1.4 you can get the same info with </p>
<pre><code>StackTraceElement[] stackTrace = new Exception().getStackTrace();
</code></pre>
| 10,882
|
<p>Among the known limitations of Joe Celko's nested sets (modified pre-order traversal) is marked degredation in performance as the tree grows to a large size.</p>
<p>Vadim Tropashko proposed nested intervals, and provides examples and theory explanation in this paper: <a href="http://arxiv.org/html/cs.DB/0401014" rel="noreferrer">http://arxiv.org/html/cs.DB/0401014</a></p>
<p>Is this a viable solution, are there any viable examples (in any language) abstracted away from the native DB layer?</p>
|
<p><a href="http://www.sitepoint.com/article/hierarchical-data-database/" rel="noreferrer">While I've seen examples for nested sets</a>, I haven't seen much for nested intervals, although in theory it shouldn't be difficult to convert from one to the other. Instead of doing pre-order traversal to label the nodes, do a breadth-first recursion. The trick is to work out the most efficient way of labelling n children of a node. Since the node between a/b and c/d is (a+c)/(b+d), an ill-conditioned insert (for instance, inserting the children left to right), runs the risk of creating the same exponential growth in the index values as, for instance, using a full <a href="http://www.dbazine.com/oracle/or-articles/tropashko4" rel="noreferrer">materialized path</a>. It is not difficult to counteract this effect - create the new indexes one at a time, inserting each at the location that produces the lowest resulting denominator.</p>
<p>As far as performance degradation goes, much depends on the operations you intend to do. There are still some operations that will require a complete relabeling of the entire tree - the nested set or nested interval methods both work best for structures that seldom change. If you are doing a lot of structure changes to the hierarchy, the 'standard' parent-child table structure may be easier to work with. remember too that some operations (such as number of descendants) are far easier with the integer labeling of nested sets than the interval methods.</p>
|
<p>I have written a gem that abstracts away all the computations of nested intervals to be used with Rails's ActiveRecord <a href="https://github.com/clyfe/acts_as_nested_interval/" rel="nofollow">https://github.com/clyfe/acts_as_nested_interval/</a> used in production on several systems.</p>
| 47,076
|
<p>I have a 12 V/30 A power supply. Will a RAMPS 1.4 shield burn if I use that power supply with it?</p>
|
<p>Voltage and current behave differently and it is important to remember two essential points:</p>
<ul>
<li>PSU voltage specifications <em><strong>should never be exceeded</strong></em>, else the circuit will (most likely) be damaged, and;</li>
<li>PSU current specifications <em><strong>can be exceeded</strong></em>, without any risk to the circuit<sup>1</sup>.</li>
</ul>
<p>So, if your circuit requires 12 V and 3 A, then the PSU must supply a maximum of 12 V, but current can be 5 A, 10 A or whatever.</p>
<p>It may help to think of it this way:</p>
<ul>
<li>Voltage will force its way into a circuit, and if you exceed the specified requirement of that circuit, then the circuit will be damaged, for sure;</li>
<li>Current passively sits there and is is only taken by the circuit as it is required - if your power supply can provide 1000 A, but the circuit only needs 11 A, then the circuit will only take 11 A. The remaining 989 A will be ignored.</li>
</ul>
<p><strong>Note</strong>: There is one caveat, where the mismatching is reversed: If a PSU can only supply 5A, but the circuit requires 10 A, then the PSU <em>may</em> be damaged as the circuit attempts to draw more current than the PSU can provide.</p>
<hr />
<h3>The water analogy</h3>
<p>You can think of electricity as similar to water in a water tank, and a tap as being the outlet/socket/circuit:</p>
<ul>
<li>The higher the water tank is above the tap, the higher the water pressure - <strong>this water pressure is analogous to voltage</strong>. If the water pressure is excessively high, then the tap could fail, in the same way that a circuit will blow,</li>
<li>The larger the tank, the more water there is that can be provided - <strong>This capacity of the tank is analogous to the current</strong>. You don't have to use, or drink, all of the water in the tank, but (often) it's nice to have an excess available, even though it might be wasteful or not particularly cost effective.</li>
</ul>
<hr />
<h3>Footnote</h3>
<p><sup>1</sup> The only major downside to having an over rated PSU with respect to current, is that should the circuit that the PSU is supplying have a issue, such as a short circuit, then a lot more current will be drawn, than if the PSU wasn't so over rated. This could be dangerous, if, for example, you are touching part of that circuit. This is why the current rating of a PSU should closely match the current requirement of the circuit which the PSU is supplying.</p>
<p>Other considerations for using an over rated PSU could (arguably) include a longer life or increased reliability. This would be due to less stress being placed upon the PSU, if the current rating of the PSU is, for example 25 - 50 % greater than the current requirement of the circuit.</p>
|
<p>No, it won't burn if you use a power supply that put out 12 Volts and tolerates up to 30 Amps.</p>
| 2,113
|
<p>I've created a custom search page with some defined options in my search scope.</p>
<p>I have a metadata mapped <code>jobtitle</code>, and added the search option to my custom search.</p>
<pre><code><Property name="JobTitle"
ManagedName="title"
ProfileURI="urn:schemas-microsoft-com:sharepoint:portal:profile:Title"/>
</code></pre>
<p>I want to change my managed name to <code>jobtitle</code>, because title doesn't hit the dutch word for jobtitle. I changed the managed name to <code>jobtitle</code>, after applying the changes it wouldn't change the label.</p>
<p>Anyone have an idea?</p>
|
<p>It is a little difficult to know exactly what you're problem is since you are using a custom search page.</p>
<p>I am assuming you created a new Managed property and mapped it to something. Then you added it to the advanced search webpart via editing the <code>xsl/xml</code> (directions <a href="http://www.sharepoint-tips.com/2006/07/found-it-how-to-add-properties-to.html" rel="nofollow noreferrer">here</a>). If you change the name of the property you just added you need to update the webpart as well.</p>
|
<p>Changes to the managed properties will not appear in the search results until the data is re-crawled. I suggest you reset the search index and do a full crawl.</p>
| 27,270
|
<p>How do I read text from the (windows) clipboard with python?</p>
|
<p>You can use the module called <a href="http://docs.activestate.com/activepython/2.5/pywin32/win32clipboard.html" rel="noreferrer">win32clipboard</a>, which is part of <a href="https://github.com/mhammond/pywin32" rel="noreferrer">pywin32</a>.</p>
<p>Here is an example that first sets the clipboard data then gets it:</p>
<pre><code>import win32clipboard
# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()
# get clipboard data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print data
</code></pre>
<p>An important reminder from the documentation:</p>
<blockquote>
<p>When the window has finished examining or changing the clipboard,
close the clipboard by calling CloseClipboard. This enables other
windows to access the clipboard. Do not place an object on the
clipboard after calling CloseClipboard.</p>
</blockquote>
|
<p>For users of Anaconda: distributions don't come with pyperclip, but they do come with pandas which redistributes pyperclip:</p>
<pre class="lang-py prettyprint-override"><code>>>> from pandas.io.clipboard import clipboard_get, clipboard_set
>>> clipboard_get()
'from pandas.io.clipboard import clipboard_get, clipboard_set'
>>> clipboard_set("Hello clipboard!")
>>> clipboard_get()
'Hello clipboard!'
</code></pre>
<p>I find this easier to use than pywin32 (which is also included in distributions).</p>
| 12,649
|
<p>In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# <code>System.Text.StringBuilder</code> and Java <code>java.lang.StringBuilder</code>.</p>
<p>Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available?</p>
|
<p>No, there is no type of stringbuilder class in PHP, since strings are mutable.</p>
<p>That being said, there are different ways of building a string, depending on what you're doing.</p>
<p>echo, for example, will accept comma-separated tokens for output.</p>
<pre><code>// This...
echo 'one', 'two';
// Is the same as this
echo 'one';
echo 'two';
</code></pre>
<p>What this means is that you can output a complex string without actually using concatenation, which would be slower</p>
<pre><code>// This...
echo 'one', 'two';
// Is faster than this...
echo 'one' . 'two';
</code></pre>
<p>If you need to capture this output in a variable, you can do that with the <a href="http://us3.php.net/outcontrol" rel="noreferrer">output buffering functions</a>.</p>
<p>Also, PHP's array performance is really good. If you want to do something like a comma-separated list of values, just use implode()</p>
<pre><code>$values = array( 'one', 'two', 'three' );
$valueList = implode( ', ', $values );
</code></pre>
<p>Lastly, make sure you familiarize yourself with <a href="http://us3.php.net/types.string" rel="noreferrer">PHP's string type</a> and it's different delimiters, and the implications of each.</p>
|
<p>no such limitation in php,
php can concatenate strng with the dot(.) operator</p>
<pre><code>$a="hello ";
$b="world";
echo $a.$b;
</code></pre>
<p>outputs "hello world"</p>
| 15,090
|
<p>I'm developing a game coded in Flash AS3 and need to read/write info to an SQL server.
Currently, for testing purposes, I use <a href="http://asql.mooska.pl/" rel="nofollow noreferrer">ASQL</a> which is very simple and robust, but it needs a direct connection from the client machine to the SQL server (port 3306 open and allowing wildcard username to connect from anywhere using a password) and the worse, the .swf format itself is not encrypted and a all decompilers will let you extract AS3 code, which means a password stored in code.</p>
<p>I have rounded up a few options but they all lack security measures:</p>
<ol>
<li>AS3 code sending a POST req to a PHP page which connects to the MySQL server</li>
<li>Use <a href="http://www.amfphp.org/" rel="nofollow noreferrer">amfphp</a>, but the AMF protocol is still sniff-able</li>
<li>Keep current method and force users to have outgoing port 3306 open, which may confuse costumers.</li>
</ol>
<p>Help/tips/discussion would be highly appreciated.</p>
|
<p>You can use HTTP(S) with authentication with e.g. PHP. Don't make the script a wrapper to the SQL connection, as this'd ruin the point of the script (essencially); have custom commands as the protocol (e.g. add/update high scores).</p>
|
<p>You can use HTTP(S) with authentication with e.g. PHP. Don't make the script a wrapper to the SQL connection, as this'd ruin the point of the script (essencially); have custom commands as the protocol (e.g. add/update high scores).</p>
| 43,492
|
<p>Using the svnmerge.py tool it is possible to merge between branches, up and down. It is hard to find the details for doing this. Hopefully, v1.5 will have a neat method for doing this without using svnmerge.py - details requested!</p>
|
<p>It looks like you're asking about 1.5 merge tracking. Here's a quick overview for doing merges to/from trunk (or another branch): <a href="http://blog.red-bean.com/sussman/?p=92" rel="nofollow noreferrer">http://blog.red-bean.com/sussman/?p=92</a></p>
|
<p>With svnmerge.py, you initialize both branches (when going in one direction, you only need to initialize one of the branches). Then merge using the -b (For bidirectional flag). Here is a summary starting from branch one to branch two. $REPO is the protocol and path to your repository.</p>
<blockquote>
<p>svn copy $REPO/branches/one $REPO/branches/two \<br>
-m "Creating branch two from branch one."<br>
svn checkout branches/one one<br>
svn checkout branches/two two</p>
<p>cd one
svnmerge init ../two<br>
cd ../two<br>
svnmerge init ../one </p>
</blockquote>
<p>You may now edit both branches. Changes from one to two can be merged by:</p>
<blockquote>
<p>cd two<br>
svnmerge merge -b -S one<br>
svn commit -F svnmerge-commit-message.txt </p>
</blockquote>
<p>Conversely, changes from two to one can be merge by:</p>
<blockquote>
<p>cd one<br>
svnmerge merge -b -S two<br>
svn commit -F svnmerge-commit-message.txt </p>
</blockquote>
<p>Be sure to note the -b flag!</p>
| 9,393
|
<p>I'm doing .NET 3.5 programming in VB for a class. I have a .mdb database with 3 related tables, and a table adapter with some queries on it that look like this:</p>
<pre><code>SELECT PropertyID, Street, Unit, City, Zip, Type, Bedrooms, Bathrooms, Area, MonthlyRent
FROM tblProperties
</code></pre>
<p>Then in a form i have a DataGridView. What i want to do is take the data that is returned from the query and display it in the DGV. However, when i do this, it displays all 35 columns in the database, not the 10 i selected (The ten are the only ones that have data in them however... so it's basically a table with a bunch of blank columns).</p>
<p>My current, inelegant solution is to return the query to a DataTable, then iterate through the table's columns, deleting the one's i dont want. This is not robust, efficient, and does not like me delete the primary key column.</p>
<p>My TA suggested trying to use an untyped databinding... he said this should display only the data I pull, but neither of us has been able to figure this out yet.</p>
<p>Thank You!</p>
<p>UPDATE</p>
<p>I'm not sure what you mean by the .aspx/.aspx.vb pages, but this is the query code i have from the table adapter</p>
<pre><code>SELECT tblRent.PaymentID, tblTenant.TenantName, tblProperties.Street, tblProperties.Unit, tblProperties.City, tblRent.AmountPaid, tblRent.PaymentDate,
tblTenant.Telephone
FROM ((tblProperties INNER JOIN
tblRent ON tblProperties.PropertyID = tblRent.PropertyID) INNER JOIN
tblTenant ON tblProperties.PropertyID = tblTenant.PropertyID)
</code></pre>
<p>and here is where i use it in code:</p>
<pre><code>Public Sub getRent()
propView.DataSource = TblPropertiesTableAdapter.GetAllRentReceipts()
propView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
propView.ReadOnly = True
End Sub
</code></pre>
<p>propView is a DataGridView that does not have a DataSource selected at load</p>
|
<p><a href="http://oss.oetiker.ch/mrtg/" rel="nofollow noreferrer">MRTG</a> is probably the easiest to setup. If your router has SNMP (as you mention), to setup it's a single command:</p>
<pre><code>cfgmaker --output=mrtg_myrouter.cfg public@1.2.3.4
</code></pre>
<p>MRTG is good for high-bandwidth routers and the likes. It's not great for other data (it can be coerced into graphing most things, but it's a little unintuitive to setup)</p>
<p>For monitoring other stuff I like <a href="http://munin.projects.linpro.no/" rel="nofollow noreferrer">Munin</a>. I would describe it again, but I posted an answer a while ago <a href="https://stackoverflow.com/questions/40737/generate-disk-usage-graphscharts-with-cli-only-tools-in-linux#43733">here</a> (about graphing disc-usage).</p>
<p>Munin can of course graph network usage, and easily pull data via SNMP (in fact it's the recommended setup for grabbing data from Windows-based servers - run a SNMP daemon on the Windows machine, and have Munin connect to this). The graphs are also prettier than MRG, I would say (clearly the most important factor..)</p>
<p>There's an example installation of <a href="http://www.switch.ch/network/operation/statistics/geant2.html" rel="nofollow noreferrer">MRTG here</a>, and <a href="http://munin.ping.uio.no/" rel="nofollow noreferrer">Munin here</a></p>
|
<p>Also consider <a href="http://cactiez.cactiusers.org/" rel="nofollow">CactiEZ</a> on a VM or small server, it is a baremetal CentOS 6 based system.</p>
| 32,220
|
<p>I'm having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn't seem to work as they keep looping when the condition is reached: </p>
<pre><code>#include<stdio.h>
#define MAX 255
int main(){
int arr[MAX]={0};
int idx=0;
/* Approach #1 */
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
while(arr[idx-1] != -1 && idx < MAX){
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}
/* Approach #2 */
do{
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}while(arr[idx-1] != -1 && idx < MAX);
// Main func continues here.
}
</code></pre>
<p>Any advice would be much appreciated!</p>
<p><strong>Update:</strong></p>
<p>Now it works! thanks MUCH <strong>all</strong> of you guys for such instant responses. This is definitely a great community, it's helping me a lot.</p>
|
<pre><code>arr[idx] <= MAX
</code></pre>
<p>should be</p>
<pre><code>idx <= MAX
</code></pre>
|
<p>C arrays begin counting from 0. </p>
<p>If you allocate an array of size MAX, accessing the element at MAX would be an error.
Change the loop to;</p>
<pre><code>int arr[MAX];
for ( .... && idx < MAX )
</code></pre>
| 13,763
|
<p>I want to download a lot of urls in a script but I do not want to save the ones that lead to HTTP errors.</p>
<p>As far as I can tell from the man pages, neither <code>curl</code> or <code>wget</code> provide such functionality.
Does anyone know about another downloader who does?</p>
|
<p>I think the <code>-f</code> option to <code>curl</code> does what you want:</p>
<blockquote>
<p><code>-f</code>, <code>--fail</code></p>
<p>(HTTP) Fail silently (no output at all) on server errors. This is mostly done to better
enable scripts etc to better deal with failed attempts. In normal cases when an HTTP
server fails to deliver a document, it returns an HTML document stating so (which often
also describes why and more). This flag will prevent curl from outputting that and
return error 22. [...]</p>
</blockquote>
<p>However, if the response was actually a 301 or 302 redirect, that still gets saved, even if its destination would result in an error:</p>
<pre><code>$ curl -fO http://google.com/aoeu
$ cat aoeu
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/aoeu">here</A>.
</BODY></HTML>
</code></pre>
<p>To follow the redirect to its dead end, also give the <code>-L</code> option:</p>
<blockquote>
<p><code>-L</code>, <code>--location</code></p>
<p>(HTTP/HTTPS) If the server reports that the requested page has moved to a different
location (indicated with a Location: header and a 3XX response code), this option will
make curl redo the request on the new place. [...]</p>
</blockquote>
|
<p>You can download the file without saving using <code>"-O -"</code> option as </p>
<pre><code>wget -O - http://jagor.srce.hr/
</code></pre>
<p>You can get mor information at <a href="http://www.gnu.org/software/wget/manual/wget.html#Advanced-Usage" rel="nofollow">http://www.gnu.org/software/wget/manual/wget.html#Advanced-Usage</a></p>
| 11,540
|
<p>Suppose I have a class where I want the user to be able to have a reference to one of my members. Which is preferred?</p>
<pre><code>class Member;
class ClassWithWeakPtr
{
private:
boost::shared_ptr<Member> _member;
public:
boost::weak_ptr<Member> GetMember();
};
</code></pre>
<p>or</p>
<pre><code>class Member;
class ClassWithCppReference
{
private:
Member _member;
public:
Member& GetMember() {return _member;}
};
</code></pre>
<p>What do you think? When is one better than another?</p>
|
<p>Why not return a <code>shared_ptr<></code>? Thatway the client gets to use what's returned for as long as he needs it, but there is no problem if the 'server' class goes away.</p>
<p>There are not too many situations where the semantics of <code>weak_ptr<></code> make a lot of sense (caches and ???). Usually when a client asks for something, it want to have ownership of that thing determined by the client itself (and shared ownership is just as good as full ownership).</p>
<p>If you have a situation where the 'server' object can be destroyed without knowledge of the client (a situation where you might want to <code>use weak_ptr<></code> or <code>shared_ptr<></code>) about the worst thing you can do is return a reference to a member. In this case, the client can't know whether or not it's safe to access the returned reference. You have to return a copy of the member or a smart pointer that can correctly manage the lifetime of the member being returned.</p>
<p>Remember that in the case where there's an expression that produces a temporary <code>ClassWithCppReference</code> (which is not always obvious), the client that calls <code>GetMember()</code> won't even be able to use the returned reference in the next statement.</p>
|
<p>Depending on the context, either one could be fine. The main problem with returning a 'live' link to a member (if you have to expose one in the first place) is that whoever uses the exposed member is that your client might hold onto it longer than the containing object exists. And if your client accesses said member via a reference when its containing object goes out of scope, you'll be facing 'odd' crashes, wrong values and similar fun. Not recommended.</p>
<p>Returning the weak_ptr<> has the major advantage that it would be able to communicate to the client that the object they are trying access is gone, which the reference can't do.</p>
<p>My 2 pennies' worth would be:</p>
<ul>
<li>If none of your clients would ever use the member, you as the author are the only person to make use of it and control the object lifetimes, returning a reference is fine. Const reference would be even better but that's not always possible in the real world with existing code.</li>
<li>If anybody else would access and use the member, especially if you are writing a library, return the weak_ptr<>. It'll save you a lot of grief and will make debugging easier.</li>
<li>I would not return a shared_ptr<>. I've seen this approach and it is usually favoured by people who are uncomfortable with the concept of a weak_ptr/weak reference. The main downside I see with it is that it will artificially extend the lifetime of another object's member beyond the scope of its containing object. That is conceptually wrong in 99% of cases and worse, can turn your programming error (accessing something that isn't there anymore) into a conceptual error (accessing something that <em>shouldn't</em> be there anymore).</li>
</ul>
| 26,474
|
<p>I used a class which derives from <code>CListBox</code>, and create it with following:</p>
<pre><code>style:WS_CHILD|WS_VISIBLE |LBS_OWNERDRAWFIXED | WS_VSCROLL | WS_HSCROLL
</code></pre>
<p>I expect the ListBox's item to be have a fixed size, not affected by the size of the list box. So I override the MeasureItem() method, in which I specify the item's size like below:</p>
<pre><code>void CMyListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMIS)
{
lpMIS->itemHeight = ALBUM_ITEM_HEIGHT;
lpMIS->itemWidth = ALBUM_ITEM_WIDTH;
}
</code></pre>
<p>But the item's size changes according to the List box's size changing. is there anything wrong with my approach?</p>
|
<p>What's not mentioned in the reference is that <code>WM_MEASUREITEM</code> is called <em>every time</em> the <code>*_OWNERDRAWFIXED</code> control is resized.</p>
<p>I don't know however, how official this behavior is and whether it should be relied on, but it has been verified at <a href="http://www.codeguru.com/Cpp/controls/listview/advanced/article.php/c1013" rel="nofollow noreferrer">CodeGuru</a> and several forum posts found on the Google thing.</p>
<p>If you don't want to process the message, then just set a private flag somewhere in the first <code>OnMeasureItem()</code> call and return from it as soon as you check that it's set next time.</p>
|
<p>If you look at the <code>MSDN</code> entry for <a href="http://msdn.microsoft.com/en-us/library/t7tccyw7(VS.80).aspx" rel="nofollow noreferrer"><code>CListBox::MeasureItem</code></a> you'll see that it's only called once unless the <code>LBS_OWNERDRAWVARIABLE</code> (not <code>LBS_OWNERDRAWFIXED</code>) style is set. If I understand correctly then this would explain the behaviour you're seeing because <code>MeasureItem</code> would need to be called each time the control's size changes.</p>
<p>Also, have you considered the points made in <a href="http://msdn.microsoft.com/en-us/library/bk2h3c6w(VS.80).aspx" rel="nofollow noreferrer">MFC Technical Note 14 : Custom Controls</a>?</p>
| 31,533
|
<p>I have a legacy VB6 executable that runs on Vista. This executable shells out another legacy MFC C++ executable.</p>
<p>In our early Vista testing, this call would display the typical UAC message to get the user's permission before running the second executable. This wasn't perfect, but acceptable. However, it now looks like this call is being completely ignored by the OS.</p>
<p>What can I do to make this call work?</p>
|
<p>If UAC is disabled on the machine, and the call would have required elevated privileges, then the call to CreateProcess will fail. make sure UAC is enabled.</p>
<p>Additionally, follow the guidelines <a href="https://stackoverflow.com/questions/90702/how-does-a-program-ask-for-administrator-privileges#90718">here for adding a UAC manifest to your program</a>.</p>
|
<p>This works well for us under Vista</p>
<pre><code>Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Type PROCESS_INFORMATION
hProcess As Long
hThread As Long
dwProcessId As Long
dwThreadId As Long
End Type
Private Type STARTUPINFO
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type
Dim ProcessInformation As PROCESS_INFORMATION
Dim StartupInformation As STARTUPINFO
Dim ReturnValue As Long
Dim NullString As String
Dim AppPathString As String
StartupInformation.cb = Len(StartupInformation)
ReturnValue = CreateProcess(NullString, AppPathString, ByVal 0&, ByVal 0&, 1&, NORMAL_PRIORITY_CLASS, ByVal 0&, NullString, StartupInformation, ProcessInformation)
'
'If you need to wait for the exe to finish
'
Do While WaitForSingleObject(ProcessInformation.hProcess, 0) <> 0
DoEvents
Loop
</code></pre>
| 14,493
|
<p>I have a product idea that requires integration into the Microsoft Office suite.</p>
<p>Are there any licensing/limitation issues to be aware of for me to proceed?</p>
|
<p>Depends...</p>
<p>If your product uses their published APIs and you don't ship any components of theirs "in your box" then you are (probably) just a value added supplier on top of their platform. You would be telling your customers to have the appropriate MS products in place and then install your App over the top. That approach is fine and the only reason you need to tell MS is because you will get a lot more business if you are a preferred/certified supplier/partner. (Depending on which product(s) you are integrating with you should check on MS to make sure that there are no specific license terms around using them).</p>
<p>If you put any of their code in your box then you have to make sure you are operating within the terms of their license and they will almost certainly make you jump through some hoops to get yourself approved by them. You also have the problem of sharing revenues which is not likely to work in your favour.</p>
<p>In my experience MS don't like doing this with anyone - regardless of size - and certainly not with really small players. </p>
<p>You may be better off approaching them directly before you start and find out if there are incubation projects that you could join to surface your idea.</p>
|
<p>I realised I have a technical answer for you too. About 10 years ago I wrote a plug-in for Excel which leveraged their spreadsheet to surface data from my provider. It was very successful and lived for about 8 years as a viable revenue generating product. It was a key differentiator for the BI company I worked for at the time.</p>
<p>The major headache in our code base was differences in API between versions of Excel, plus different DLL dependencies. MS like to say that they don't break their APIs between releases but this is not actually true. They may have got better at it, but it was always a real issue for us getting hold of a pre-release version of their new software to see what we had to do to keep ours working with it. Then we had to support several different Ecel versions and upgrade of our content between them. All in all it added a huge amount of complexity to our lives.</p>
<p>Their APIs have changed significantly in style, and Office is much more open than it was, but you asked for considerations and this is certainly one.</p>
| 29,215
|
<p>I am currently working on a project that will store specific financial information about our clients in a MS SQL database. Later, our users need to be able to query the database to return data from the clients based on certain criteria (eg. clients bigger then a certain size, clients in a certain geographical location) and total it to use as a benchmark. The database will be accessed by our financial software using a script.</p>
<p>I am currently writing the stored procedures for the database. What I am planning on doing is writing several different stored procedures based on the different types of criteria that can be used. They will return the client numbers.</p>
<p>The actual question I have is on the method of retrieving the data. I need to do several different calculations with the clients data. Is it better practice to have different stored procedures to do the calculation based on the client number and return the result or is it better to just have a stored procedure return all the information about the client and perform the calculations in the script?</p>
<p>Performance could be an issue because there will be a lot of clients in the database so I want the method to be reasonably efficient.</p>
|
<p>Interestingly, the data warehouse folks do this all the time. They often use the simplest possible SQL (SELECT SUM/COUNT... GROUP BY...) and do the work <em>outside</em> the database in report-writing tools.</p>
<p>I think you should get a copy of The Data Warehouse Toolkit and see how this can be done in a way that's quite a bit simpler. more flexible and probably more scalable.</p>
|
<p>You can do any calculation in stored procedure and return data. Interest calculation like stored procedure need lot of calculations. </p>
<p>Any way you have to calculate data with other table data's. </p>
<p>SUM we can do in SP,</p>
<pre><code>Declare @SUMAmount decimal(12,3)
</code></pre>
<p>-- also declare @A, @B etc</p>
<pre><code>Select @SUMAmount= SUM(ISNULL(@A,0)+ISNULL(@B,0)+ISNULL(@C,0)+ISNULL(@D,0))
Select @SUMAmount= SUM((ISNULL(@A,0)+ISNULL(@B,0))*(ISNULL(@C,0)-ISNULL(@D,0)))
</code></pre>
<p>As per your requirement you can give condition.</p>
<p>ISNULL is using for check whether data is NULL then return 0. Calculation with Null value is not possible so better give ISNULL condition.</p>
<pre><code>Select A,B,SUM(C),D From TableName
Where SUM(C)>0
Group By A,B,D
</code></pre>
<p>Here Both aggregate and non aggregate functions are there so you have to use Group By.
You can get values as per your condition eg: "Where SUM(C)>0". Having also you can use here after Group By.</p>
<pre><code> Declare @TotalNoofDays int
@TotalNoofDays = DATEDIFF(d, fromdate, todate)
</code></pre>
<p>Using for find number of days using this function.</p>
<p>You can use condition like,</p>
<pre><code>if @DueAmount >=0
BEGIN
IF @DiscountFlag = 1
BEGIN
SET @DueIntAmount = 0
END
ELSE
BEGIN
SET @DueIntAmount = ((@DueAmount*(@IntRateOnDue/100))/365)*@NoofDays
END
SET @ExcessInterestAmount = 0
END
ELSE
BEGIN
SET @DueIntAmount = 0
SET @ExcessInterestAmount = ((@DueAmount*(@IntRateOnDeposit/100))/365)*@NoofDays
END
</code></pre>
<p>Like calculations you can do in Stored Procedure.</p>
<p>If you want to do calculations with number of records one by one then you can use temporary table while loop..</p>
<pre><code> Create Proc NewLearningProcedure
(
@Name Varchar(50),
@Date DateTime
)
AS
Begin
Declare @Temp Table
(
ID int Identity(1,1),
Name Varchar(50),
Date DateTime
)
Insert Into @Temp
Select @Name,@Date
Declare @i int
set @i=10
While @i>0
Begin
Insert Into @Temp
Select @Name+CAST(@i as varchar(50)),@Date
Set @i=@i-1
End
Select * from @Temp
End
</code></pre>
<p>Like you can do anything with Stored Procedure.</p>
| 21,117
|
<p>I've been beating myself over the head with this app migration for a few days now. What I have is an old MSSQL Server 2000-backed application that is being upgraded to a Windows 2003 Server running SMSQL Server 2005. I know little about SQL Server but obviously not enough.</p>
<p>I tried backing up the database on the old server by going to Databases->[Database]->All Tasks->Backup Database..., selecting 'Full', and saving the file. I moved that backup file to the new server and tried to do a restore but it complained saying that it was looking for the [Database].mdf file in the location it was on the old server.</p>
<p>So then I tried to do an Export Data, selected the local SQL 2000 database, pointed it to the new SQL 2005 database on the other machine, and it gets all the way to the end and dies complaining about the way one of the tables is being joined.</p>
<p>I tried then doing a 'Generate SQL' command on the 2000 box and running that under SQL 2005. It looks like there are a lot of outer joins using the old *= syntax that SQL Server 2005 doesn't support anymore and, this being a vendor database, have no idea what their true intentions were when they set up these tables.</p>
<p>Is there any other way I can try migrating this database over?</p>
|
<p>The backup file has the "hard" location of the data files stored in it. You just need to update them:</p>
<p>When you restore in 2005, before you click the final "ok" to restore (after you have selected the .bak file), go to the options tab. This will have the mdf and ldf locations that were in the backup file. Change these to legitimate directories on your new machine.</p>
|
<p>Create a backup of SQL2000's database to file. Create new database on SQL2005 with same name and restore backup file into new database with option "force restore over existing database" and set copliant level of new database to "SQL2000 (8.0)".</p>
| 18,682
|
<p>I'd like to have my Eclipse plugin cause a URL to be opened by the users' default browser. This seems like pretty standard behavior, but I haven't been able to find any docs on how to do this.</p>
<p>Can anyone help?</p>
|
<p>You are looking for:</p>
<pre><code>final IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport().createBrowser( ... );
browser.openURL(url);
</code></pre>
|
<p>Do you mean launch an external windows (IE, FireFox, ...) outside eclipse, or opening an internal "<a href="http://kickjava.com/src/org/eclipse/swt/browser/Browser.java.htm" rel="nofollow noreferrer">Browser</a>" composite ?</p>
<p>Because on the internal side, the <a href="http://kickjava.com/src/org/eclipse/help/ui/internal/browser/embedded/EmbeddedBrowser.java.htm" rel="nofollow noreferrer">org.eclipse.help.ui.internal.browser.embedded.EmbeddedBrowser</a> seems to be able to define any kind of major browser.</p>
<p>To open the default user's browser (as an internal or external window) is a preference defined in General/Web browser.</p>
| 38,425
|
<p>What is the best technique for catching ALL exceptions thrown within JavaScript?</p>
<p>Obviously, the best technique is to use try...catch. But with ansynchronous callbacks and so forth, that can get tricky.</p>
<p>I know IE and Gecko browsers support window.onerror, but what about Opera and Safari?</p>
<p>Here are a bunch of test-cases that I would like to have a central exception handling solution for:</p>
<pre><code>// ErrorHandler-Test1
var test = null;
test.arg = 5;
// ErrorHandler-Test2
throw (new Error("Hello"));
// ErrorHandler-Test3
throw "Hello again";
// ErrorHandler-Test4
throw {
myMessage: "stuff",
customProperty: 5,
anArray: [1, 2, 3]
};
// ErrorHandler-Test5
try {
var test2 = null;
test2.arg = 5;
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test6
try {
throw (new Error("Goodbye"));
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test7
try {
throw "Goodbye again";
} catch(e) {
ErrorHandler.handleError(e);
}
// ErrorHandler-Test8
try {
throw {
myMessage: "stuff",
customProperty: 5,
anArray: [1, 2, 3]
};
} catch(e) {
ErrorHandler.handleError(e);
}
</code></pre>
<p>If you think of any other test-cases, please mention them. Several of these cases mention a ErrorHandler.handleError method. This is just a suggested guideline when using try...catch.</p>
|
<p>If you use a library like <a href="http://jquery.com/" rel="noreferrer">jQuery</a> for assigning all your event handlers, you can use a combination of <code>window.onerror</code> and wrapping the jQuery event handler code and on ready function with an error handling function (see: <a href="http://blogs.cozi.com/tech/2008/04/javascript-error-tracking-why-windowonerror-is-not-enough.html" rel="noreferrer">JavaScript Error Tracking: Why window.onerror Is Not Enough</a>).</p>
<ul>
<li><code>window.onerror</code>: catches all errors in IE (and most errors in Firefox), but does nothing in Safari and Opera.</li>
<li>jQuery event handlers: catches jQuery event errors in all browsers.</li>
<li>jQuery ready function: catches initialisation errors in all browsers.</li>
</ul>
|
<p>I was also looking for error handling and stacktrace and logging for user actions this is what i found hope this also helps you
<a href="https://github.com/jefferyto/glitchjs" rel="nofollow">https://github.com/jefferyto/glitchjs</a></p>
| 25,198
|
<p>There are so many Linux distributions to choose from! What is the "best" linux flavor for a web hosting environment running primarily:
Apache HTTP, Tomcat or JBoss, MySQL and Alfresco (not necessarily all in the same instance).</p>
<p>Are there any significant differences in terms of ease of administration and configuration, performance and stability for such applications, etc.?</p>
<p>What would you recommend?</p>
<p>Thanks!
Mike</p>
|
<p>They all use similar tools to administer things like webmin, and sshd.</p>
<p>What are you more familiar with. Red Hat based systems(fedora, mandriva) or Debian based systems(Ubuntu). This family divide will determine a few things. First rpm packaging vs deb packaging.</p>
<p>You also want to look at the level of activity of the project. Mandriva and Ubuntu are two examples of active distributions. That try to keep up with current releases of software.</p>
<p>Other than that most stuff performs with little difference.</p>
|
<p>You mentioned Linux and Java. You did <em>not</em> mention other things like an Appserver, LDAP server, DB Server. </p>
<p>With those things considered, you would be best off with Redhat, Fedora, CentOS and SUSE/OpenSUSE. Ubuntu will not hurt since they have a relationship with Sun but since JBoss has become part of REdhat, I would think that Redhat-based distros should be pretty good.</p>
<p>I've used Redhat/Fedora and OpenSUSE to run banking production apps and they are pretty good. Dell offers good support for Redhat + JAVA + ORACLE.</p>
| 16,656
|
<p>Is there a way in C# to play audio (for example, MP3) direcly from a <a href="http://msdn.microsoft.com/en-us/library/system.io.stream%28v=vs.110%29.aspx" rel="noreferrer">System.IO.Stream</a> that for instance was returend from a WebRequest without saving the data temporarily to the disk?</p>
<hr>
<h3>Solution with <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a></h3>
<p>With the help of <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a> 1.3 it is possible to:</p>
<ol>
<li>Load an MP3 file from a URL into a MemoryStream</li>
<li>Convert MP3 data into wave data after it was completely loaded</li>
<li>Playback the wave data using <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a>'s WaveOut class</li>
</ol>
<p>It would have been nice to be able to even play a half loaded MP3 file, but this seems to be impossible due to the <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a> library design.</p>
<p>And this is the function that will do the work:</p>
<pre><code> public static void PlayMp3FromUrl(string url)
{
using (Stream ms = new MemoryStream())
{
using (Stream stream = WebRequest.Create(url)
.GetResponse().GetResponseStream())
{
byte[] buffer = new byte[32768];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
}
ms.Position = 0;
using (WaveStream blockAlignedStream =
new BlockAlignReductionStream(
WaveFormatConversionStream.CreatePcmStream(
new Mp3FileReader(ms))))
{
using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
{
waveOut.Init(blockAlignedStream);
waveOut.Play();
while (waveOut.PlaybackState == PlaybackState.Playing )
{
System.Threading.Thread.Sleep(100);
}
}
}
}
}
</code></pre>
|
<p><strong>Edit: Answer updated to reflect changes in recent versions of NAudio</strong></p>
<p>It's possible using the <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a> open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the <code>MP3Frame</code> and <code>AcmMp3FrameDecompressor</code> classes in NAudio to decompress streamed MP3 on the fly.</p>
<p>I have posted an article on my blog explaining <a href="http://mark-dot-net.blogspot.com/2011/05/how-to-play-back-streaming-mp3-using.html" rel="noreferrer">how to play back an MP3 stream using NAudio</a>. Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a <code>BufferedWaveProvider</code>. Another thread then plays back using the <code>BufferedWaveProvider</code> as an input.</p>
|
<p>I've always used FMOD for things like this because it's free for non-commercial use and works well.</p>
<p>That said, I'd gladly switch to something that's smaller (FMOD is ~300k) and open-source. Super bonus points if it's fully managed so that I can compile / merge it with my .exe and not have to take extra care to get portability to other platforms...</p>
<p>(FMOD does portability too but you'd obviously need different binaries for different platforms)</p>
| 22,336
|
<p>I have 1 table called urltracker that holds information about the number of times a specific url has been clicked. The table is structured into 4 columns id, urlclicked, referrer and timestamp. The urltracker creates another entry in the table every time a url has been clicked.</p>
<p>What i would like to do is display a specific url and the number of times it has been clicked, the user would then be able to drill down into the data by clicking to reveal all the specific times this url has been clicked.</p>
<p>I'm no sql expert but this sounds like i need to initially display all the distinct URL's followed by a sub query which displays all the entries for this specfic url.</p>
<p>Am i right in thinking this or is there an easier way?</p>
|
<p>One thing to consider is using two tables - one table that holds the unique urls and another that stores the click information (and either using a unique sequence number to join them, or the url (since it is unique))</p>
<p>But to answer your query question - yes I would have one query to display URLs and a second query to get the data for a specific URL (only if/when the user requests that info).</p>
|
<p>You should be able to do something like this to get the totals for each URL:</p>
<pre><code>SELECT urlclicked, COUNT(urlclicked) AS total
FROM urltracker
GROUP BY urlclicked
</code></pre>
<p>Is this what you were after?</p>
| 49,443
|
<p>I have a web app that is heavily loaded in javascript and css. First time users log in it takes some time to load once it is downloading js etc. Then the caching will make everything faster.</p>
<p>I want my users to be aware of this loading time. How can I add some code to "show" some loading information while js and css are downloaded?</p>
|
<p>You could show an overlay saying "loading..." and hide this the moment the downloads are complete.</p>
<pre><code><html>
<head>
... a bunch of CSS and JS files ...
<script type="text/javascript" src="clear-load.js"></script>
</head>
<body>
<div
style="position: absolute; left: 50px; right: 50px; top: 50px; bottom: 50px; border: 3px solid black;"
id="loading-div"
>
This page is loading! Be patient!
</div>
... Your body content ...
</body>
</html>
</code></pre>
<p>Contents of clear-load.js:</p>
<pre><code>document.getElementById('loading-div').style.display = 'none';
</code></pre>
<p>Of course, you could also tack the javascript code that hides the div at the bottom of the last javascript file that's loaded.</p>
<p>Also, try to pack your javascript and css files into one file and apply gzip compression or "minify" to them. You can bring 500KB of javascript in 20 requests to 1 request of less than 100KB if you do it right.</p>
|
<p>Sweet mother of mercy, Ricardo, how much Javascript and CSS are involved with this application?</p>
<p>You could, I guess, do something where you load the JS and CSS using an AJAX request and do nothing with them. This will load your JS and CSS files into the cache. You could do all of this on a "Loading" page, and redirect to the real page once you've loaded the files. But IMO you really shouldn't have to do this. Use <a href="http://www.fiddlertool.com/fiddler/" rel="nofollow noreferrer">Fiddler</a> to really see what's going on behind the scenes -- make sure people are really having to wait for their JS/CSS files to come down before doing this optimization.</p>
| 38,724
|
<p>Before anyone suggests scrapping the table tags altogether, I'm just modifying this part of a very large system, so it really wouldn't be wise for me to revise the table structure (the app is filled with similar tables).</p>
<p>This is a webapp in C# .NET - data comes in from a webservice and is displayed onscreen in a table. The table's rows are generated with asp:Repeaters, so that the rows alternate colers nicely. The table previously held one item of data per row. Now, essentially, the table has sub-headers... The first row is the date, the second row shows a line of data, and all the next rows are data rows until data of a new date comes in, in which case there will be another sub-header row.</p>
<p>At first I thought I could cheat a little and do this pretty easily to keep the current repeater structure- I just need to feed some cells the empty string so that no data appears in them. Now, however, we're considering one of those +/- collapsers next to each date, so that they can collapse all the data. My mind immediately went to hiding rows when a button is pressed... but I don't know how to hide rows from the code behind unless the row has a unique id, and I'm not sure if you can do that with repeaters.</p>
<p>I hope I've expressed the problem well. I'm sure I'll find a way TBH but I just saw this site on slashdot and thought I'd give it a whirl :)</p>
|
<p>When you build the row in the databinding event, you can add in a unique identifier using say the id of the data field or something else that you use to make it unique.</p>
<p>Then you could use a client side method to expand collapse if you want to fill it with data in the beginning, toggling the style.display setting in Javascript for the table row element.</p>
|
<p><strike>just wrap the contents of the item template in an asp:Panel, then you have you have a unique id.</strike> Then throw in <a href="http://www.learningjquery.com/2007/03/accordion-madness" rel="nofollow noreferrer">some jquery</a> for some spice ;)</p>
<p><strong>edit</strong>: just noticed that you are using a table. put the id on the row. then toggle it.</p>
| 10,267
|
<p>I always wondered what different methods Google Desktop Search is using so that it uses least CPU and memory while indexing a computer containing more 100,000 files on an average.</p>
<p>In just few hours it has indexed the whole system and I did not see it eating up my CPU, memory etc.</p>
<p>If any of you have done some research, please do share.</p>
|
<p>The trick is simple: It starts to work then very soon stops and just sits there in in memory, doing nothing. Of course it's then totally useless but at least, it keeps light and fast. Sorry, couldn't resist :-) I Switched to Windows Search 4.0 and I'm much happier about it.</p>
|
<p>It doesn't...</p>
<p>I installed it on one computer, and quickly removed it because it was intrusive (although this can be probably configured) and hungry (particularly on a low end PC).</p>
<p>It is installed on a laptop near me right now, and if I compare it to a couple of small utilities I run permanently (SlickRun, CLCL, my AutoHotkey script...) it uses more than 10 times their CPU and 5 to 20 times their memory. Times two, since, for some reason, I have one instance running another, plus the ToolbarNotifier (less hungry).<br>
Even Trend Micro anti-virus uses less memory and CPU.</p>
<p>Perhaps I will try it again when I will get a more modern PC with lot of memory, but right now I am happy enough with some grep utilities, even if they are slower.</p>
| 24,487
|
<p>I've been attempting move a directory structure from one location to another in Subversion, but I get an <code>Item '*' is out of date</code> commit error. </p>
<p>I have the latest version checked out (so far as I can tell). <code>svn st -u</code> turns up no differences other than the mv commands.</p>
|
<p>I sometimes get this with TortoiseSVN on windows. The solution for me is to <code>svn update</code> the directory, even though there are no revisions to download or update. It does something to the metadata, which magically fixes it.</p>
|
<p>is more isyly make this:</p>
<p>1)i copy my modify code in a notepad.
2) next , update the file.
3) copy the code of notepad in a file updated.
4) commit in svn.</p>
| 11,359
|
<p>I am trying to get the <code>Edit with Vim</code> context menu to open files in a new tab of the previously opened Gvim instance (if any).</p>
<p>Currently, using <code>Regedit</code> I have modified this key:</p>
<pre><code>\HKEY-LOCAL-MACHINE\SOFTWARE\Vim\Gvim\path = "C:\Programs\Vim\vim72\gvim.exe" -p --remote-tab-silent "%*"
</code></pre>
<p>The registry key type is <code>REG_SZ</code>.</p>
<p>This almost works... Currently it opens the file in a new tab, but it also opens another tab (which is the active tab) the tab is labeled <code>\W\S\--literal</code> and the file seems to be trying to open the following file. </p>
<pre><code>C:\Windows\System32\--literal
</code></pre>
<p>I think the problem is around the <code>"%*"</code> - I tried changing that to <code>"%1"</code> but if i do that I get an extra tab called <code>%1</code>.</p>
<p><strong>Affected version</strong></p>
<ul>
<li>Vim version 7.2 (same behaviour on 7.1) </li>
<li>Windows vista home premium</li>
</ul>
<p>Thanks for any help. </p>
<p>David. </p>
|
<p>Try setting it to: "C:\Programs\Vim \vim72\gvim.exe" -p --remote-tab-silent "%1" "%*"</p>
<p>See: <a href="http://www.vim.org/tips/tip.php?tip_id=1314" rel="noreferrer">http://www.vim.org/tips/tip.php?tip_id=1314</a></p>
<p>EDIT: As pointed out by Thomas, vim.org tips moved to: <a href="http://vim.wikia.com/" rel="noreferrer">http://vim.wikia.com/</a></p>
<p>See: <a href="http://vim.wikia.com/wiki/Add_open-in-tabs_context_menu_for_Windows" rel="noreferrer">http://vim.wikia.com/wiki/Add_open-in-tabs_context_menu_for_Windows</a></p>
|
<p>I would recommend trying <a href="http://cream.sourceforge.net/index.html" rel="nofollow noreferrer">Cream</a>.</p>
<p> Cream is a set of scripts and add-ons that sit on top of gVim. Cream doesn't change the appearance of gVim, but it does change the way it behaves.</p>
<p>One of those behaviours is a tabbed document interface. Other behaviours are listed <a href="http://cream.sourceforge.net/featurelist.html" rel="nofollow noreferrer">here</a>. The downloads page is <a href="http://cream.sourceforge.net/download.html" rel="nofollow noreferrer">here</a>.</p>
| 9,306
|
<p>I recently had to solve this problem and find I've needed this info many times in the past so I thought I would post it. Assuming the following table def, how would you write a query to find all differences between the two?</p>
<p>table def:</p>
<pre><code>CREATE TABLE feed_tbl
(
code varchar(15),
name varchar(40),
status char(1),
update char(1)
CONSTRAINT feed_tbl_PK PRIMARY KEY (code)
CREATE TABLE data_tbl
(
code varchar(15),
name varchar(40),
status char(1),
update char(1)
CONSTRAINT data_tbl_PK PRIMARY KEY (code)
</code></pre>
<p>Here is my solution, as a view using three queries joined by unions. The <code>diff_type</code> specified is how the record needs updated: deleted from <code>_data(2)</code>, updated in <code>_data(1)</code>, or added to <code>_data(0)</code></p>
<pre><code>CREATE VIEW delta_vw AS (
SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 0 as diff_type
FROM feed_tbl LEFT OUTER JOIN
data_tbl ON feed_tbl.code = data_tbl.code
WHERE (data_tbl.code IS NULL)
UNION
SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 1 as diff_type
FROM data_tbl RIGHT OUTER JOIN
feed_tbl ON data_tbl.code = feed_tbl.code
where (feed_tbl.name <> data_tbl.name) OR
(data_tbl.status <> feed_tbl.status) OR
(data_tbl.update <> feed_tbl.update)
UNION
SELECT data_tbl.code, data_tbl.name, data_tbl.status, data_tbl.update, 2 as diff_type
FROM feed_tbl LEFT OUTER JOIN
data_tbl ON data_tbl.code = feed_tbl.code
WHERE (feed_tbl.code IS NULL)
)
</code></pre>
|
<p>UNION will remove duplicates, so just UNION the two together, then search for anything with more than one entry. Given "code" as a primary key, you can say:</p>
<p><em>edit 0: modified to include differences in the PK field itself</em></p>
<p><em>edit 1: if you use this in real life, be sure to list the actual column names. Dont use dot-star, since the UNION operation requires result sets to have exactly matching columns. This example would break if you added / removed a column from one of the tables.</em></p>
<pre><code>select dt.*
from
data_tbl dt
,(
select code
from
(
select * from feed_tbl
union
select * from data_tbl
)
group by code
having count(*) > 1
) diffs --"diffs" will return all differences *except* those in the primary key itself
where diffs.code = dt.code
union --plus the ones that are only in feed, but not in data
select * from feed_tbl ft where not exists(select code from data_tbl dt where dt.code = ft.code)
union --plus the ones that are only in data, but not in feed
select * from data_tbl dt where not exists(select code from feed_tbl ft where ft.code = dt.code)
</code></pre>
|
<p>I would use a minor variation in the second <code>union</code>:</p>
<pre><code>where (ISNULL(feed_tbl.name, 'NONAME') <> ISNULL(data_tbl.name, 'NONAME')) OR
(ISNULL(data_tbl.status, 'NOSTATUS') <> ISNULL(feed_tbl.status, 'NOSTATUS')) OR
(ISNULL(data_tbl.update, '12/31/2039') <> ISNULL(feed_tbl.update, '12/31/2039'))
</code></pre>
<p>For reasons I have never understood, <code>NULL</code> does not equal <code>NULL</code> (at least in SQL Server).</p>
| 5,084
|
<p>This has got to be something simple: I set up a frames page with two possible sources for the target frame based on a form with two options. I used the OnClick event to trap the user's click to show the appropriate page. It works fine in Internet Explorer 7, swapping the two source pages. FireFox 3 and Chrome show only the default source.</p>
<p>HEAD Script section:</p>
<pre><code>function SwapInlineFrameSource()
{
var rsRadio, rsiFrame;
rsRadio=document.getElementById('County');
rsiFrame=document.getElementById('RatesFrame')
if (rsRadio.checked===true) {
rsiFrame.src="SantaCruzRates.htm";
}
else {
rsiFrame.src="DelNorteRates.htm";
}
}
</code></pre>
<p>BODY Form section (commented to show up here):</p>
<pre><code><input type="radio" value="SC" checked name="County" onclick="SwapInlineFrameSource()">
Santa Cruz
<input type="radio" value="DN" name="County" onclick="SwapInlineFrameSource()" >
Del Norte
</code></pre>
<p>What am I missing? (Live example: <a href="http://www.raintrees.com/rates.html" rel="nofollow noreferrer">http://www.raintrees.com/rates.html</a>)</p>
<p>Thanks!</p>
<p>mr</p>
|
<p>You are using getElementByID, but you aren't specifying IDs for your inputs. Perhaps consider this instead:</p>
<pre><code>function SwapInlineFrameSource(rdoButton)
{
rsiFrame = document.getElementById("RatesFrame");
rsiFrame.src = rdoButton.value;
}
<input type="radio" value="SantaCruzRates.htm" checked="checked" name="County" onClick="SwapInlineFrameSource(this);">Santa Cruz</input>
<input type="radio" value="DelNorteRates.htm" name="County" onClick="SwapInlineFrameSource(this);">Del Norte</input>
</code></pre>
|
<p>I don't believe that getElementById works on frames in firefox. I have always used the frames["frameID"], which seems to work more consistently.</p>
| 35,008
|
<p>I am trying to pass a dataString to to an ajax call using JQuery. In the call, I construct the get parameters and then send them to the php page on the receiving end. The trouble is that the data string has ampersands in them and the HTML strict validator is chocking on it.</p>
<p>Here is the code:</p>
<pre><code>$(document).ready(function(){
$("input#email").focus();
$('#login_submit').submit(function(){
var username = $('input#email').val();
var password = $('input#password').val();
var remember = $('input#remember').attr("checked");
var dataString = "email="+username+"&password="+password+"&remember="+remember;
$.post('login.php', dataString, function(data) {
if (data == 'Login Succeeded.') {
location.reload(true);
} else {
$("input#email").focus();
$("#login_msg").html(data).effect("pulsate", {times: 2}, 1000);
}
});
return false;
});
});
</code></pre>
<p>and here is an example of the validator message: cannot generate system identifier for general entity "password".</p>
<pre><code>var dataString = "email="+username+"&password="+password+"&remember="+rememb…
</code></pre>
<p>(in the validator the "p" after the first ampersand is marked red indicating the point of the failure).</p>
|
<p>Try putting your javascript inside a CDATA block like this:</p>
<pre><code><script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>
</code></pre>
<p>which should make it pass validation. To be extra safe you can add Javascript comments around the CDATA tags to hide them from older browsers who don't understand the CDATA tag:</p>
<pre><code><script type="text/javascript">
/* <![CDATA[ */
// content of your Javascript goes here
/* ]]> */
</script>
</code></pre>
|
<p>i would try:</p>
<pre><code>var dataString = "email="+username+"&amp;password="+password+"&amp;remember="+remember;
</code></pre>
| 46,270
|
<p>As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database.</p>
<p>I know that technically this would be an integration test (not a unit test), but I want to find out the best strategies for the following:</p>
<ol>
<li>Testing queries. </li>
<li>Testing inserts. How do I know that the insert that has gone wrong if it fails? I can test it by inserting and then querying, but how can I know that the query wasn't wrong? </li>
<li>Testing updates and deletes -- same as testing inserts</li>
</ol>
<p>What are the best practices for doing these?</p>
<hr>
<p>Regarding testing SQL: I am aware that this could be done, but if I use an O/R Mapper like NHibernate, it attaches some naming warts in the aliases used for the output queries, and as that is somewhat unpredictable I'm not sure I could test for that.</p>
<p>Should I just, abandon everything and simply trust NHibernate? I'm not sure that's prudent.</p>
|
<p>Look into DB Unit. It is a Java library, but there must be a C# equivalent. It lets you prepare the database with a set of data so that you know what is in the database, then you can interface with DB Unit to see what is in the database. It can run against many database systems, so you can use your actual database setup, or use something else, like HSQL in Java (a Java database implementation with an in memory option).</p>
<p>If you want to test that your code is using the database properly (which you most likely should be doing), then this is the way to go to isolate each test and ensure the database has expected data prepared.</p>
|
<p>I would also mock the database, and check that the queries are what you expected. There is the risk that the test checks the wrong sql, but this would be detected in the integration tests</p>
| 2,426
|
<p>Yes we all get a <b>warm and fuzzy</b> feeling when we read about project specifications, and how they help keep a project <b>on time</b> and <b>within scope</b> etc etc.</p>
<p>Who here actually works for a company that keeps and up-to-date specification?</p>
<p>If you do, what are the reasons for this? Is the primary reason that you have a large team?</p>
|
<p>Cor.. <strong>What's a project spec?</strong></p>
<p>We tend to start out with an idea that has well defined timelines etc. then the sales team talk to the customer and promise the Earth. Our project spec then goes out the window!</p>
<p>So, we do not maintain a project spec mainly because:</p>
<ul>
<li>Sales promise too much.</li>
<li>We have a small team and not a lot of time can be taken off coding for documentation.</li>
<li>We often have to turn around any changes VERY quickly (often ASAP), which leaves little/no time to update any documentation if there were any!</li>
</ul>
<p>Do I think all of this is good? <strong>No!</strong> But at this time, it's hard to see a way out of it for us! Lots to do (both work wise and process improvement).</p>
<p>My home projects seem to be much better, but my specs are also a lot looser, and I know how I work - I therefore can gear the process to work much more in tune with me.</p>
|
<p>The best way to do this is to extract out the relevant bits of the func. / design spec. and then include them as "headers" in the actual code.</p>
<p>These headers can then be extracted using Javadoc or some such.</p>
<p>That way developers can update the "header" when they update the code and it keeps the whole project in synch.</p>
<p>Works pretty will for us.</p>
| 45,652
|
<p>Sorry, that title just hurts. I'm wondering if there is a Linq to collections extension method that collapses the following code segment into a single line:</p>
<pre><code>public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents){
var result = new List<Child>();
foreach(Parent parent in parents)
foreach(Child child in parent.Children)
result.Add(child);
return result;
}
</code></pre>
<p>If you can collapse that into a single statement, try it on insane difficulty:</p>
<pre><code>public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas){
var result = new List<Child>();
foreach(Grandparent papa in nanas)
foreach(Parent parent in papa.Children)
foreach(Child child in parent.Children)
result.Add(child);
return result;
}
</code></pre>
|
<p>Here's the obligatory method form.</p>
<pre><code>return parents
.SelectMany(p => p.Children);
</code></pre>
<p>And for two levels:</p>
<pre><code>return oldies
.SelectMany(grand => grand.Children)
.SelectMany(parent => parent.Children);
</code></pre>
|
<p>This will work:</p>
<pre><code>public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents)
{
return from parent in parents
from child in parent.Children
select child;
}
</code></pre>
<p>and then this:</p>
<pre><code>public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas)
{
return from papa in nanas
from parent in papa.Children
from child in parent.Children
select child;
}
</code></pre>
<p>Note, in this example I'm not actually returning a list, I'm returning an IEnumerable data source that until you start to foreach over it, or similar, won't actually do any processing.</p>
<p>If you need to return a list, modify each return statement as follows:</p>
<pre><code> return (from .....
...
select child).ToList();
</code></pre>
| 25,131
|
<p>Assume you have some objects which have several fields they can be compared by:</p>
<pre><code>public class Person {
private String firstName;
private String lastName;
private String age;
/* Constructors */
/* Methods */
}
</code></pre>
<p>So in this example, when you ask if:</p>
<pre><code>a.compareTo(b) > 0
</code></pre>
<p>you might be asking if a's last name comes before b's, or if a is older than b, etc...</p>
<p>What is the cleanest way to enable multiple comparison between these kinds of objects without adding unnecessary clutter or overhead?</p>
<ul>
<li><code>java.lang.Comparable</code> interface allows comparison by one field only</li>
<li>Adding numerous compare methods (i.e. <code>compareByFirstName()</code>, <code>compareByAge()</code>, etc...) is cluttered in my opinion.</li>
</ul>
<p>So what is the best way to go about this?</p>
|
<p>With Java 8: </p>
<pre><code>Comparator.comparing((Person p)->p.firstName)
.thenComparing(p->p.lastName)
.thenComparingInt(p->p.age);
</code></pre>
<p>If you have accessor methods:</p>
<pre><code>Comparator.comparing(Person::getFirstName)
.thenComparing(Person::getLastName)
.thenComparingInt(Person::getAge);
</code></pre>
<p>If a class implements Comparable then such comparator may be used in compareTo method:</p>
<pre><code>@Override
public int compareTo(Person o){
return Comparator.comparing(Person::getFirstName)
.thenComparing(Person::getLastName)
.thenComparingInt(Person::getAge)
.compare(this, o);
}
</code></pre>
|
<p>Its easy to do using <a href="http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained#equals" rel="nofollow noreferrer">Google's Guava library</a>.</p>
<p>e.g. <code>Objects.equal(name, name2) && Objects.equal(age, age2) && ...</code></p>
<p>More examples:</p>
<ul>
<li><a href="https://stackoverflow.com/a/5039178/1180621">https://stackoverflow.com/a/5039178/1180621</a></li>
</ul>
| 48,263
|
<p>I believe it's the <code>File</code> class but I heard that is very expensive in memory.</p>
<p>Is there a better way to work with file paths?</p>
|
<p>It's hard to say without knowing what you want to do, but please do not prematurely optimize. I doubt the memory use of a File object will be at all noticeable in your application.</p>
|
<p>The only time I know where File uses a lot of memory is when you use File.list()...</p>
<p>See these for some solutions:</p>
<p><a href="https://stackoverflow.com/questions/354703/is-there-a-workaround-for-javas-poor-performance-on-walking-huge-directories">Is there a workaround for Java’s poor performance on walking huge directories?</a></p>
| 48,133
|
<p>I can select all the distinct values in a column in the following ways:</p>
<ul>
<li><code>SELECT DISTINCT column_name FROM table_name;</code></li>
<li><code>SELECT column_name FROM table_name GROUP BY column_name;</code></li>
</ul>
<p>But how do I get the row count from that query? Is a subquery required?</p>
|
<p>You can use the <code>DISTINCT</code> keyword within the <a href="http://technet.microsoft.com/en-us/library/ms175997%28v=sql.90%29.aspx" rel="noreferrer"><code>COUNT</code></a> aggregate function:</p>
<pre><code>SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name
</code></pre>
<p>This will count only the distinct values for that column.</p>
|
<p>Count(distinct({fieldname})) is redundant</p>
<p>Simply Count({fieldname}) gives you all the distinct values in that table. It will not (as many presume) just give you the Count of the table [i.e. NOT the same as Count(*) from table]</p>
| 17,109
|
<p>Is there a native c++ variable type that's "bigger" than a double?<br>
float is 7<br>
double is 15 (of course depending on the compiler)<br>
Is there anything bigger that's native, or even non-native?</p>
|
<p>C++ has <code>long double</code>, but there is no guarantee that it's any more precise than a plain <code>double</code>. On an x86 platform, usually <code>double</code> is 64 bits, and <code>long double</code> is either 64 or 80 bits (which gives you 19 significant figures, if I remember right).</p>
<p>Your mileage may vary, especially if you're not on x86.</p>
|
<p>Boost 1.53 or higher has multiprecision.</p>
<p><a href="http://www.boost.org/doc/libs/1_54_0/libs/multiprecision/doc/html/index.html" rel="nofollow">http://www.boost.org/doc/libs/1_54_0/libs/multiprecision/doc/html/index.html</a></p>
| 32,113
|
<p>I have a tree representation of pages in a CMS application. I understand how to persist the tree in the database. However, I don't have a good way to:</p>
<p>A) Reorder subpages under a particular parent page.<br>
B) Provide a UI implementation that allows the user to change the order.</p>
<p>Any suggestions?</p>
|
<p><a href="http://www.javaworld.com/javaworld/jw-12-2004/jw-1220-toolbox.html" rel="nofollow noreferrer">Write custom appenders for log4j</a></p>
|
<p>May I suggest that you leverage the existing SyslogAppender?</p>
| 6,934
|
<p>I'm programming a class that implements the observable pattern (not the interface) and I'm thinking about whether or not the copy constructor should also copy the listeners.</p>
<p>On the one hand the copy constructor should create an instance that is as close as possible to the original instance so that it can be swapped out in the display context.</p>
<p>On the other hand this would assume the listeners can cope with that kind of thing.</p>
<p>Any thoughts? Are there any best practices?</p>
|
<p>Don't copy. The listeners are not aware of the new object and are not expecting to receive messages related to it.</p>
|
<p>Don't copy.</p>
| 39,400
|
<p>(using the IMAP commands, not with the assistance of any other mail package)</p>
|
<p>I'm not sure how well-versed you are in imap-speak, but basically after login, "SELECT" the source mailbox, "COPY" the messages, and "EXPUNGE" the messages (or "DELETE" the old mailbox if it is empty now :-).</p>
<pre><code>a login a s
b select source
c copy 1 othermbox
d store 1 +flags (\Deleted)
e expunge
</code></pre>
<p>would be an example of messages to send. (<strong>Note</strong>: imap messages require a uniqe prefix before each command, thus the "a b c" in front)</p>
<p>See <a href="http://james.apache.org/server/rfclist/imap4/rfc2060.txt" rel="noreferrer">RFC 2060</a> for details.</p>
|
<p>I guess you COPY the message to the new folder and then delete (EXPUNGE) it in the old one.</p>
<p><a href="http://www.networksorcery.com/enp/rfc/rfc3501.txt" rel="nofollow noreferrer">RFC3501</a></p>
<p><strong>HINT</strong> There's no DELETE command that does what you mean, you have to flag the message as deleted and then EXPUNGE the mailbox. Have a look at the RFC. Be careful with DELETE, as it deletes whole mailboxes, not single mails.</p>
| 14,868
|
<p>Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them? </p>
|
<p>You've been able to run rubygems under IronRuby for quite a while now. Simply download and install the latest <a href="http://www.codeplex.com/Wikipage?ProjectName=ironruby" rel="noreferrer">IronRuby from codeplex</a>, and run <code>igem</code> on the command line</p>
<hr />
<blockquote>
<p><strong>Original Answer:</strong></p>
<p>I'm on that mailing list - to save you the digging, someone asked this a few weeks ago, and <a href="http://rubyforge.org/pipermail/ironruby-core/2008-August/002688.html" rel="noreferrer">this was the answer</a></p>
<p>The answer (at this point) is no, you can't, but it doesn't seem like it'll be too far away.</p>
<p>PS: listen to curt. He's on the core team for ironruby. <3</p>
</blockquote>
|
<p>if you set ENV['GEM_PATH'] correctly before using rubygems, then gems will work <em>sometimes</em> under IronRuby. I'm actually looking at fixing this right now.</p>
<p>Also, this kind of question is probably better suited for the <a href="http://rubyforge.org/mail/?group_id=4359" rel="nofollow noreferrer">IronRuby mailing list</a> than it is for StackOverflow.</p>
| 6,676
|
<p>I'm using a <code>std::map</code> (VC++ implementation) and it's a little slow for lookups via the map's find method. </p>
<p>The key type is <code>std::string</code>.</p>
<p>Can I increase the performance of this <code>std::map</code> lookup via a custom key compare override for the map? For example, maybe <code>std::string</code> < compare doesn't take into consideration a simple <code>string::size()</code> compare before comparing its data?</p>
<p>Any other ideas to speed up the compare?</p>
<p>In my situation the map will always contain < 15 elements, but it is being queried non stop and performance is critical. Maybe there is a better data structure that I can use that would be faster?</p>
<p>Update: The map contains file paths.</p>
<p>Update2: The map's elements are changing often.</p>
|
<p>First, turn off all the profiling and DEBUG switches. These can slow down STL immensely.</p>
<p>If that's not it, part of the problem may be that your strings are identical for the first 80-90% of the string. This isn't bad for map, necessarily, but it is for string comparisons. If this is the case, your search can take much longer. </p>
<p>For example, in this code find() will likely result in a couple of string compares, but each will return after comparing the first character until "david", and then the first three characters will be checked. So at most, 5 characters will be checked per call.</p>
<pre><code>map<string,int> names;
names["larry"] = 1;
names["david"] = 2;
names["juanita"] = 3;
map<string,int>::iterator iter = names.find("daniel");
</code></pre>
<p>On the other hand, in the following code, find() will likely check 135+ characters:</p>
<pre><code>map<string,int> names;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/wilma"] = 1;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/fred"] = 2;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/barney"] = 3;
map<string,int>::iterator iter = names.find("/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/betty");
</code></pre>
<p>That's because the string comparisons have to search deeper to find a match since the beginning of each string is the same.</p>
<p>Using size() in your comparison for equality won't help you much here since your data set is so small. A std::map is kept sorted so its elements can be searched with a binary search. Each call to find should result in less than 5 string comparisons for a miss, and an average of 2 comparisons for a hit. But it does depend on your data. If most of your path strings are of different lengths, then a size check like Motti describes could help a lot.</p>
<p>Something to consider when thinking of alternative algorithms is how many many "hits" you get. Are most of your find() calls returning end() or a hit? If most of your find()s return end() (misses) then you are searching the entire map every time (2logn string compares). </p>
<p>Hash_map is a good idea; it should cut your search time in about half for hits; more for misses. </p>
<p>A custom algorithm may be called for because of the nature of path strings, especially if your data set has common ancestry like in the above code.</p>
<p>Another thing to consider is how you get your search strings. If you are reusing them, it may help to encode them into something that is easier to compare. If you use them once and discard them, then this encoding step is probably too expensive.</p>
<p>I used something like a Huffman coding tree once (a long time ago) to optimize string searches. A binary string search tree like that may be more efficient in some cases, but its pretty expensive for small sets like yours.</p>
<p>Finally, look into alternative std::map implementations. I've heard bad things about some of VC's stl code performance. The DEBUG library in particular is bad about checking you on every call. <a href="http://stlport.sourceforge.net/" rel="noreferrer">StlPort</a> used to be a good alternative, but I haven't tried it in a few years. I've always loved <a href="http://www.boost.org/" rel="noreferrer">Boost</a> too.</p>
|
<p><code>hash_map</code> is not standard, try using <code>unordered_map</code> available in tr1 (which is available in boost if your tool chain doesn't already have it).</p>
<p>For small numbers of strings you might be better using <code>vector</code>, as <code>map</code> is typically implemented as a tree.</p>
| 31,950
|
<p>I'm looking for an explanation or good free online resources about the organization of memory and memory management in Windows systems.</p>
|
<p>You can buy this (old) book, (the actual Windows architecture hasn't really changed much in 10 years) for a penny (used):</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/1572316772" rel="noreferrer" rel="nofollow noreferrer">Inside Windows NT</a></p>
<p>Here's the up-to-date version:</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0735619174" rel="noreferrer" rel="nofollow noreferrer">MS Windows Internals</a></p>
<p>There's also <a href="http://blogs.technet.com/markrussinovich/" rel="noreferrer">Mark's Blog</a></p>
<p>As far as ONLINE resources go, I've found it to be pretty sparse, though :(</p>
|
<p>In MSDN, some information is located here: <a href="http://msdn.microsoft.com/en-us/library/aa366525(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa366525(VS.85).aspx</a></p>
| 43,280
|
<p>I've been asked to create a Delphi compatible dll in C++ to do simple 64bit memory management.</p>
<p>The background is that the system in Delphi needs to allocate a lots of chunks of memory that would go well outside 32bit addressable space. The Delphi developer explained to me that he could not allocate memory with the Delphi commands available to him. He says that he can hold a 64bit address, so he just wants to call a function I provide to allocate the memory and return a 64bit pointer to him. Then another function to free up the memory later.</p>
<p>Now, I only have VS 2008 at my disposal so firstly I'm not even sure I can create a Delphi compatible dll in the first place.</p>
<p>Any Delphi experts care to help me out. Maybe there is a way to achieve what he requires without re-inventing the wheel. Other developers must have come across this before in Delphi.</p>
<p>All comments appreciated.</p>
|
<p>Only 64 bit processes can address 64 bit memory. A 64 bit process can only load 64 bit dlls and 32 bits processes can only load 32 bits dlls. Delphi's compiler can only make 32 bits binaries.</p>
<p>So a 32 bits Delphi exe can not load your 64 bit c++ dll. It could load a 32 bit c++ dll, but then that dll wouldn't be able to address the 64 bit memory space. You are kind of stuck with this solution.</p>
<p>Delphi could, with the right compiler options and Windows switches address 3GB of memory without problems. Even more memory could be accessed by a 32 bits process if it uses <a href="http://en.wikipedia.org/wiki/Physical_Address_Extension" rel="nofollow noreferrer">Physical Address Extension</a>. It then needs to swap memory pages in and out of the 32 bits memory through the use of <a href="http://msdn.microsoft.com/en-us/library/aa366527(VS.85).aspx" rel="nofollow noreferrer">Address Windowing Extensions</a>.</p>
|
<p>You might also want to add a way to pin and unpin that 64-bit pointer to a 32-bit memory address. Since this is Delphi, I'm pretty sure it's Windows specific, so you might as well use <a href="http://msdn.microsoft.com/en-us/library/aa366527(VS.85).aspx" rel="nofollow noreferrer">Address Windowing Extensions</a>. That way, you can support allocating, freeing, and pinning and unpinning memory to a 32-bit address range and still take advantage of a 64-bit memory allocation space. Assuming that the user will actually commit the memory such that it fits in the 32-bit virtual address space.</p>
| 5,448
|
<p>Can anyone give me an example of what the Artifact paths setting defined for a build configuration could look like if I want to create two artifacts dist and source where I am using the sln 2008 build runner and building my projects using the default bin/Release?</p>
<pre>
**/Source/Code/MyProject/bin/Release/*.* => dist
**/*.* => source
</pre>
<p>I get two artifact roots dist and source but under dist I get the whole directory structure (Source/Code/MyProject/bin/Release) which I don't want and under source I get the whole thing along with obj and bin/Release which I do not want.</p>
<p>Can you give some advice on how to do this correctly?</p>
<p>Do I need to change the target location for all the projects I am building to be able to get this thing to work?</p>
|
<p>So you'll just need:</p>
<pre><code>Source\Code\MyProject\bin\Release\* => dist
Source\**\* => source
</code></pre>
<p>This will put all the files in release into a artifact folder called dist and everything in Source into a artifact folder called source.</p>
<p>If you have subfolders in Release try:</p>
<pre><code>Source\Code\MyProject\bin\Release\**\* => dist
</code></pre>
|
<p>According to TeamCity documentation; it should be like this:</p>
<pre><code>file_name|directory_name|Ant-like wildcard [ => target_directory ]
</code></pre>
<p>So.. </p>
<pre><code>Source\Code\MyProject\bin\Release|**\* => dist (| not \)
</code></pre>
| 21,997
|
<p>What is the clearest explanation of what computer scientists mean by "the naive implementation"? I need a good clear example which will illustrate — ideally, even to non-technical people — that the naive implementation may <em>technically</em> be a functioning solution to the problem, but <em>practically</em> be utterly unusable.</p>
|
<p>I'd try to keep it away from computers altogether. Ask your audience how they find an entry in a dictionary. (A normal dictionary of word definitions.)</p>
<p>The naive implementation is to start at the very beginning, and look at the first word. Oh, that's not the word we're looking for - look at the next one, etc. It's worth pointing out to the audience that they probably didn't even <em>think</em> of that way of doing things - we're smart enough to discount it immediately! It is, however, about the simplest way you could think of. (It might be interesting to ask them whether they can think of anything simpler, and check that they do really understand why it's simpler than the way we actually do it.)</p>
<p>The next implementation (and a pretty good one) is to start in the middle of the dictionary. Does the word we're looking for come before or after that? If it's before, turn to the page half way between the start and where we are now - otherwise, turn to the page half way between where we are now and the end, etc - binary chop.</p>
<p>The actual human implementation is to use our knowledge of letters to get very rapidly to "nearly the right place" - if we see "elephant" then we'll know it'll be "somewhere near the start" maybe about 1/5th of the way through. Once we've got to E (which we can do with very, very simple comparisons) we find EL etc.</p>
|
<p>A O(n!) algorithm.</p>
<pre><code>foreach(object o in set1)
{
foreach(object p in set1)
{
// codez
}
}
</code></pre>
<p>This will perform fine with small sets and then exponentially worse with larger ones.</p>
<p>Another might be a naive Singleton that doesn't account for threading.</p>
<pre><code>public static SomeObject Instance
{
get
{
if(obj == null)
{
obj = new SomeObject();
}
return obj;
}
}
</code></pre>
<p>If two threads access that at the same time it's possible for them to get two different versions. Leading to seriously weird bugs.</p>
| 32,108
|
<p>I can't figure out a use case for being able to annotate interfaces in Java. </p>
<p>Maybe someone could give me an example?</p>
|
<p>I've used it in Spring to annotate interfaces where the annotation should apply to all subclasses. For example, say you have a Service interface and you might have multiple implementations of the interface but you want a security annotation to apply regardless of the annotation. In that case, it makes the most sense to annotate the interface.</p>
|
<p>You could use it for contract style programming - go one step further than just defining the interface (types and method names) and also define some semantics (contents of the types, preconditions, postconditions).</p>
<p>I'd have to check up on how annotations work in Java though, but this stuff could easily be done with Python annotations...</p>
| 17,634
|
<p>Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?</p>
<p>I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.</p>
<p><strong>Edit:</strong> From link provided in accepted answer:</p>
<p>Include Silverlight.js (from Silverlight SDK)</p>
<pre><code>Silverlight.isInstalled("2.0");
</code></pre>
|
<p>Include Silverlight.js (from Silverlight SDK)</p>
<p><code>Silverlight.isInstalled("4.0")</code></p>
<hr>
<p><strong>Resource:</strong></p>
<p><a href="http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx</a></a></p>
|
<pre><code>var hasSilverlight = Boolean(window.Silverlight);
var hasSilverlight2 = hasSilverlight && Silverlight.isInstalled('2.0');
</code></pre>
<p>Etc....</p>
| 14,590
|
<p>Here is my code: </p>
<pre><code>ThreadStart threadStart = controller.OpenFile;
Thread thread = new Thread(threadStart);
thread.Start();
</code></pre>
<p>In the OpenFile function, my code looks like:</p>
<pre><code>System.Console.Error.WriteLine("Launching");
</code></pre>
<p>The code in OpenFile doesn't get executed for 30 seconds exactly. It starts immediately on my machine, but in our production environment it takes 30 seconds before that print statement will execute.</p>
<p>Is there a setting or something that might be doing this? Where would I start looking?</p>
|
<p>As others pointed out - first try to produce a test program which demonstrates the behavior.</p>
<p>If you can't, try to troubleshoot by:
1. Call the method directly, not in thread, and see how it behaves.
2. Comment out the rest of the code besides the System.Error.WriteLine line</p>
<p>If you still see the the delay in (1), but not in (2), then try to attach to <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyload.aspx" rel="nofollow noreferrer">AppDomain.AssemblyLoad Event</a>. I have seen this happen when in the called method there is a call to a web service (it generates a serialization assembly on the fly, so it takes time), or if there is a first reference to external assembly, and it takes time to find and load it. It's very rare, but I had to deal with this, so it's worth trying.</p>
|
<p>My first step would be to build a test version of the app that calls the OpenFile function the normal way (without using threads), and see if you still get the delay.</p>
| 35,213
|
<p>How do you do your Hibernate session management in a Java Desktop Swing application? Do you use a single session? Multiple sessions?</p>
<p>Here are a few references on the subject:</p>
<ul>
<li><a href="http://www.hibernate.org/333.html" rel="noreferrer">http://www.hibernate.org/333.html</a></li>
<li><a href="http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/" rel="noreferrer">http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/</a> </li>
<li><a href="http://in.relation.to/Bloggers/HibernateAndSwingDemoApp" rel="noreferrer">http://in.relation.to/Bloggers/HibernateAndSwingDemoApp</a></li>
</ul>
|
<p>Single session. Start transaction when you need to do a set of operations (like update data after dialog box OK button), commit the tx at the end. The connection though is constantly open (since it's the same session), and thus all opportunities for caching can be used by both Hib and RDBMS.</p>
<p>It may also be a good idea to implement a transparent session re-open in case the connection went dead -- users tend to leave applications open for extended periods of time, and it should continue to work Monday even if DB server was rebooted on weekend.</p>
<p><strong>Update</strong></p>
<p>Jens Schauder provided a reason to use multiple sessions: partial (unwanted) updates to the session. Well, that comes down to the way you use Hibernate. </p>
<p>Suppose we have two dialogs open (as in Jens' blog example). If user clicks a radiobox, and we immediately update a Hibernate entity associated with this radiobox, then, when user clicks Cancel, we're in trouble -- session is already updated.</p>
<p>The right way, as I see it, is to update dialog variables (non-Hibernate objects) only. Then, when user clicks OK, we begin a transaction, merge updated objects, commit the transaction. No garbage gets ever saved into session.</p>
<pre><code>MyHibernateUtils.begin();
Settings settings = DaoSettings.load();
// update setttings here
DaoSettings.save(settings);
MyHibernateUtils.commit();
</code></pre>
<p>If we implement such a clean separation of concerns, we can later switch to multiple sessions with a simple change of MyHibernateUtils.begin() implementation.</p>
<p>As for possible memory leak, well... Transaction.commit() calls Session.flush(), which AFAIK, cleans the cache too. Also, one may manually control the caching policy by calling Session.setCacheMode().</p>
|
<p>Use one session per thread (<a href="http://www.hibernate.org/42.html#A6" rel="nofollow noreferrer">doc</a>) and a version or timestamp column to allow optimistic concurrency and thereby avoiding session-to-instance conflicts. Attach instances to session when needed unless you need long running transactions or a restrictive isolation level.</p>
| 33,720
|
<p>Probably the question sounds a little strange; however, I am looking for a filament which is breakable and not so steady and reliable as PLA. I want to print parts similar to the following gears for instance (They are from Lego, a children's toy). <a href="https://i.stack.imgur.com/dsvt3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dsvt3.png" alt="enter image description here"></a></p>
<p>They should break after some time or in any way become unusable after an accidental period (1 minute to several days) of use. Yes, you read right: I want to print parts that are frangible and probably will break! I plan to use Ultimaker 3 as 3D printer. So I'm looking for a suitable filament. Maybe I can merge two types of filament?</p>
<p>Could Ultimaker's TPU filament (<a href="https://ultimaker.com/en/products/materials/tpu-95a" rel="nofollow noreferrer">https://ultimaker.com/en/products/materials/tpu-95a</a>) be useful for my purpose? Or can anybody recommend me another filament that can be useful for my intended use? The primary purpose is that the printed part is not stable enough to serve its original purpose for longer than a foreseeable time (1 minute to several days). I appreciate your advice and ideas.</p>
<hr>
<p>Note: I don't want to sell them; I want to use them for my <strong>private</strong> project. So please no legal issues. They are not helpful for my question. I don't ask for legal advice.</p>
|
<h2>deliberate/planned obsolescence is the term you look for</h2>
<p>If you design parts that break after some time, you plan their obsolescence. That you do by a deliberate choice of material and working conditions. Designing a part that will break after a certain time can be done by choosing the correct stresses that will make your chosen material break.</p>
<p>In a gear that is meant to break at certain stress, one can weaken the teeth or the sprues, so that normal operation stresses will very likely break the safety margin and destroy the gear.</p>
<h2>is it a material choice?</h2>
<p>Any material is suitable to make a planned break, as long as <em>the design</em> is suitable. Performing a stress analysis of your part will tell you where to weaken it to enforce it will break - if the part was solid. As printed parts in FDM aren't solid, take the result with salt - it will tell <em>where</em> but not <em>when</em> it fails. Do the experiment for actual numbers.</p>
<h2>is it a print setting thing?</h2>
<p>Besides deliberately under-engineering some part of the gear, a usually perfectly fine gear would lose a lot of strength by deliberately reducing how massive it is: the stability of a print is affected by the form and amount of the infill just as much as the number of shells. Some random setting examples:</p>
<ul>
<li>1-shelled, 1-bottom/top-layer, 5% infill piece is very likely so fragile you might not get it off the build plate</li>
<li>these parameters at 2-5-10% results in a somewhat durable piece.</li>
<li>2-5-20% is more than twice as strong as 2-5-10%.</li>
</ul>
<p>To find the exact breaking point of a setup, one might need to toy with the parameters and experiment. It might be interesting to use no top- or bottom-layers and thus turn to create all the <em>spokes</em> of the gear in the shape of infill and outer shell. Also, some infills are better at withstanding forces than others - for example, Gyroid or Hex infill is rather stable on pressure while spaghetti is quite weak.</p>
<p>Other parameters also can change the infill stability: speeding up the print of the infill compared to the shell and using a thinner line considerably weakens the infill, thus reducing the needed load to break it. This is a somewhat easy parameter to tweak if you want to go for breaking the spokes (see below).</p>
<h2>planned obsolescence and how to under-engineer safely</h2>
<p>Sometimes, planned destruction is good for safety: a safety valve is supposed to break under overpressure to release the pressure in a safe way.</p>
<p>But planned obsolescence can also be a safety risk: If a toy breaks under normal use, it is a safety hazard for the broken off parts can be swallowed by children. Another factor to look at is where broken off parts end up in the machinery - they might jam other pieces that are not meant to self-destruct and destroy them.</p>
<ul>
<li>Design the pieces to break in a safe way - the larger the chunks, the better you prevent them from going into places they should not.</li>
<li>Design the teeth to deform or melt rather than shearing off</li>
<li>Design the axles to sheer free by losing their keying</li>
<li>Design the spokes of the gears to break, separating gear rim from axle & hub, either of which goes nowhere due to the other gears and the mounting</li>
<li>Encase the self-destruct gears in some sort of gearbox to prevent the pieces from going flying</li>
</ul>
<p>Industrial machinery design usually goes the melting way: Let's take a hand mixer. It contains a gearset that has one drive gear connected to a second gear, so that both mixers spin opposite. Under normal use, these spin pretty fast, creating heat from the friction. In a good design, these two gears are made from metal or a high heat tolerant polymer. But if one plans for having them break, these gears are made from a material that will heat under the friction in such a way, that after a set time (around 5 minutes), the teeth will be sufficiently weakened to deform and grind away, destroying them in the process.</p>
<h2>Preferred Material</h2>
<p>I would actually deliberately under-design the gears for the expected loads and then go for a solid material printed in SLA or SLS from either a resin (which will break with pieces and bits going flying, so a gearbox is mandatory!) or a polyamide (nylon). These parts would match the stress analysis fully.</p>
<p>If FDM is the only option, the material choice depends on the failure mode you opted for:</p>
<ul>
<li>In case you opt for destruction from heat on the teeth or axle, a low melting material like PLA is perfectly fine, but make sure to engineer the chance of breaking teeth low. ABS can perform a little better but needs more heat (and thus more RPM) to self destruct.</li>
<li>In case of designing for a breaking failure of spokes or keying, PLA is an excellent choice, as it is sufficiently brittle.</li>
<li>PETG is a good compromise between ABS deformability and PLA's printing ease.</li>
</ul>
<hr />
<h3>Footnotes</h3>
<p>Gear Design<br><sup>When designing your gears, keep in mind that gears are rather complicated. I actually advise to take a look on the gross oversimplification of <a href="https://www.youtube.com/watch?v=Q-XOM4E4RZQ" rel="nofollow noreferrer">This Old Tony</a> because it allows you to see where you can make teeth break very easily by design!</sup></p>
<p>planned obsolescence and consumer rights<br><sup>While planned obsolescence can be an important safety factor, planning obsolescence in consumer products for sale to break them after a calculated time is unethical and can be a <a href="https://www.twobirds.com/en/news/articles/2018/global/planned-obsolescence-and-consumers-rights" rel="nofollow noreferrer">consumer rights violation.</a> Remember, that legally demanded warranty and a right to repair exist in <a href="https://equiterre.org/en/news/legislation-against-obsolescence" rel="nofollow noreferrer">a lot of countries.</a></sup></p>
<p>LEGO is Copyrighted, Patented and Trademarked<br><sup>Copying Lego designs would be a Trademark Violation, Patent infringement <strong>and</strong> a <a href="https://www.copyright.gov/circs/circ15a.pdf" rel="nofollow noreferrer">copyright</a> violation by using their designs. They <a href="https://www.beemlaw.com/billion-dollar-lego-patent/" rel="nofollow noreferrer">protect</a> them.</sup></p>
|
<p>This metod will be difficult with gears but doable. Print cold and slightly under extruded. This will cause part to fail in layers. You may need to print the part on side to ensure a non functioning gear. Use PLA or PETG. Breaking TPU is next to impossible.</p>
| 1,197
|
<p>What are the main differences when using ABS over PLA and vice versa?</p>
|
<p>Paraphrasing <a href="http://www.protoparadigm.com/news-updates/the-difference-between-abs-and-pla-for-3d-printing/">this</a> site. Feel free to add suggestions in the form of comments and I will try to incorporate them.</p>
<p>Summary</p>
<ul>
<li>ABS: Stronger, machinable, more flexible, and more temperature
resistant than PLA. Typically printed on a heated bed. Warping is a common problem when printing ABS.</li>
<li>PLA: Wider range of filaments available, easier and in some cases faster to print. Not as strong as ABS and the fact that its biodegradable could be seen as both a benefit and a drawback.</li>
</ul>
<p>Material Properties:</p>
<ul>
<li>ABS: Strong plastic with mild flexibility. Naturally beige in color. Can be filled and sanded. Higher temperature. Easy to recycle.</li>
<li>PLA: Not as strong as ABS but more rigid. Naturally transparent. More difficult to fill and sand. Can sag in hot temperatures. Sourced from organic matter so it can be broken down in commercial compost facilities.</li>
</ul>
<p>Part Accuracy:</p>
<ul>
<li>ABS: Part warping is a significant issue. Sharp corners will often be rounded.</li>
<li>PLA: Less heat required contributes to less warping. Becomes more liquid at common extruder temperatures so finer details can be printed.</li>
</ul>
<p>Safety and Handling:</p>
<ul>
<li>ABS: Strong burning/melting plastic smell is present when printing ABS. Health concerns have been raised regarding airborne ultrafine particles generated while printing with ABS (<a href="https://dx.doi.org/10.1016%2Fj.atmosenv.2013.06.050">ref</a>). ABS will absorb moisture causing popping when the moisture enters the hot end. This leads to discontinuities in the print job.</li>
<li>PLA: Doesn't smell as strongly when printing due to its organic nature. Moisture can also be absorbed into PLA and can irreversibly damage it.</li>
</ul>
|
<p>PLA (polylactic acid) melts at a lower temp and does not warp AS BADLY when cooled. It is non-toxic (in USA it comes from cornstarch, beets in some countries, or tapioca root)
It is less flexible than ABS, could rip or crumble.</p>
<p>ABS (Acrylonitrile Butadiene Styrene) is a harder and more sturdy plastic. (What Legos are made of). A heated bed is used to keep it from cooling too fast, as warping can be a problem is you cool it too fast (being close to an exterior door or an air vent) An enclosed printer helps regulate temp and avoids SOME of this problem. Some people get headaches from the smell of molten ABS over a prolonged time. It flexes better than PLA. Can be sanded or cut easily and maintain integrity.</p>
<p>Beware of CHEAP ABS as it may contain a higher amount of HCN (Hydrogen Cyanide)
that can be released when used (but usually around 1 part per million, about one fourth the dangerous limit.)</p>
<p>"GOOD" ABS CAN contain HCN as well, but it is not released by "normal" printing temperatures. (avoid burning ABS or Nylon)</p>
<p>so, all in all:
PLA is safe/non-toxic, biodegradable, uses less energy to print, less flexible.</p>
<p>ABS is harder, sturdier, will last nearly forever (if not bent or stressed or frozen). Somewhat flexible and will snap back. </p>
| 86
|
<p>Is there any clear documentation on the binary formats used to serialize the various MFC data structures? I've been able to view some of my own classes in a hex editor and use Java's ByteBuffer class to read them in (with automatic endianness conversions, etc).</p>
<p>However, I am currently running into issues while trying to bring over the CObArray data, as there seems to be a rather large header that is opaque to me, and it is unclear how it is persisting object type information.</p>
<p>Is there a set of online documentation that would be helpful for this? Or some sample Java code from someone that has dealt with this in the past?</p>
|
<p>Since MFC ships with source code I would create a test MFC application that serializes a CObArray and step through the serialization code. This should give you all the information you need.</p>
|
<p>I agree with jmatthias: use the MFC source code.</p>
<p>There's also <a href="http://msdn.microsoft.com/en-us/library/32wxt301%28VS.71%29.aspx" rel="nofollow noreferrer">this page</a> on MSDN that may be useful.</p>
| 7,911
|
<p>What's the regex to match a square bracket? I'm using <code>\\]</code> in a pattern in <code>eregi_replace</code>, but it doesn't seem to be able to find a <code>]</code>...</p>
|
<p><code>\]</code> is correct, but note that PHP itself ALSO has <code>\</code> as an escape character, so you might have to use <code>\\[</code> (or a different kind of string literal).</p>
|
<p>You problem may come from the fact you are using eregi_replace with the first parameter enclosed in simple quotes:</p>
<pre><code> '\['
</code></pre>
<p>In <a href="http://us2.php.net/manual/en/language.types.string.php#language.types.string.syntax.double" rel="nofollow noreferrer">double quotes</a>, though, it could works well depending on the context, since it <a href="http://www.weberdev.com/get_example-3838.html" rel="nofollow noreferrer">changes the way the parameter</a> is passed to the function (simple quotes just pass the string without any interpretation, hence the need to double to "\" character).</p>
<p>Here, if <code>"\["</code> is interpreted as an escape character, you still need to double "\".</p>
<p>Note: based on your comment, you may try the regex</p>
<pre><code><\s*(?:br|p)\s*\/?\s*\>\s*\[
</code></pre>
<p>in order to detect a <code>[</code> right after a <code><br></code>or a <code><p></code></p>
| 45,435
|
<p>As I've only ever used Visual Studio for .NET development, I would like to expand my horizons and see what else there is on offer as an alternative to it. So what in your opinion is the best alternative to Visual Studio? Is there a viable alternative?</p>
|
<p>If you're into C# and VB.Net and don't mind open source then you could use <a href="http://www.icsharpcode.net/OpenSource/SD/" rel="noreferrer">SharpDevelop</a>. It does a pretty good job!</p>
|
<p>For .NET development, VS2008 is the best but if you want to check for another best IDE, <strong><a href="http://www.eclipse.org/downloads/" rel="nofollow noreferrer">Eclipse</a></strong> probably the best after VS if you are rating it among the IDEs, ofcourse you cant do .NET development in Eclipse though</p>
| 40,044
|
<p>WSPBuilder</p>
<p>Version: 0.9.8.0830
Created by Carsten Keutmann
GPL License 2007</p>
<p>Install and deploying [MYDLL]
Unable to deploy solution
Inner exception(1): This solution contains one or more assemblies targeted for the global assembly cache. You should use a strong name for any assembly that will be in the global assembly cache.</p>
|
<p>I had the same issues but what worked for me was to delete all the files in the bin and obj folder and then rebuild the WSP.</p>
|
<p>I'm experiencing the same issue, one solution, multiple projects, the one failing to compile is using an object from another project.</p>
<p>I've tried clearing the bin & obj folder, as well as restarting the server. I think I'll copy the files dll to the gac using gacutil instead.</p>
| 48,507
|
<p>Which is better? Or use and OR mapper with SP's? If you have a system with SP's already, is an OR mapper worth it? </p>
|
<p>I like ORM's because you don't have to reinvent the wheel. That being said, it completely depends on your application needs, development style and that of the team.</p>
<p>This question has already been covered <a href="https://stackoverflow.com/questions/50346/why-is-parameterized-sql-generated-by-nhibernate-just-as-fast-as-a-stored-proce">Why is parameterized SQL generated by NHibernate just as fast as a stored procedure?</a></p>
|
<p>I personally have found that SP's tend to be faster performance wise, at least for the large data items that I execute on a regular basis. But I know many people that swear by OR tools and wouldn't do ANYTHING else.</p>
| 10,856
|
<p>I'm new to this JSF world, please bear with me if I'm asking some silly thing</p>
<p>i'm using UI tags for my application and I have a scenario that I need to generate a calendar control to make the user to select the date I followed the ui tags documentation and wrote the code like this:</p>
<pre><code> <table width="100%">
<tr>
<td>
<ui:calendar binding="#{booking.calDate}"
id="calDate"
dateFormatPattern="dd/MM/yyyy"
label="Date ::"/>
</td>
</tr>
</table>
</code></pre>
<p>and my backing bean contains</p>
<pre><code> private Calendar calDate = new Calendar();
</code></pre>
<p>with appropriate getters and setters</p>
<p>when I tried to load the page I'm getting the calendar component disorted.
I'm getting cross marks and nonsense things with some javascript errors.</p>
<p>please help me in resolving this issue</p>
<p>Thanks in anticipation</p>
|
<p>I got the solution by myself - the issue is with the javascript code. it reads the javascript from themes.jar, which i placed in web-inf/lib folder still it was unable to access that. so I extracted the same and placed it in web-inf and it's working fine</p>
|
<p>The component is coming from which JSF library?
In others words, what do you have at the beginning of your XHTML file?</p>
<p>The only library I know is coming from <a href="https://facelets.dev.java.net/" rel="nofollow noreferrer">Facelets</a>, and it does not provide any component!</p>
<p>In addition, if calDate is a **java.util.**Calendar class, then you cannot bind this class to a JSF component!</p>
<p>Maybe you can have a look to <a href="http://myfaces.apache.org/tomahawk-project/tomahawk12/tagdoc/t_inputCalendar.html" rel="nofollow noreferrer">Tomahawk</a>, or <a href="http://livedemo.exadel.com/richfaces-demo/richfaces/calendar.jsf" rel="nofollow noreferrer">Richfaces</a>, that provide good calendar component...</p>
| 43,187
|
<p>How can I <strong>pre pend</strong> (insert at beginning of file) a file to all files of a type in folder and sub-folders using <code>Powershell</code>?</p>
<p>I need to add a standard header file to all <code>.cs</code> and was trying to use <code>Powershell</code> to do so, but while I was able to append it in a few lines of code I was stuck when trying to <strong>pre-pend</strong> it.</p>
|
<p>Here is a very simple example to show you one of the ways it could be done.</p>
<pre><code>$Content = "This is your content`n"
Get-ChildItem *.cs | foreach-object {
$FileContents = Get-Content -Path $_
Set-Content -Path $_ -Value ($Content + $FileContents)
}
</code></pre>
|
<p>Have no idea, but if you have the code to append just do it the other way round. Something like</p>
<ol>
<li>rename existing file,</li>
<li>create an empty file named the same as above </li>
<li>append header to new empty file,</li>
<li>append renamed file to previous,</li>
<li>delete renamed file</li>
</ol>
| 9,959
|
<p>I'm using Zend Studio 6.1 for Eclipse, which comes bundled with the Subversive plug-in.</p>
<p>My repo layout is:</p>
<pre><code>/trunk/
/branches/
/tags/
</code></pre>
<p>My application code is in:</p>
<pre><code>/trunk/application
</code></pre>
<p>I'm trying to add some view templates in:</p>
<pre><code>/trunk/application/views/tags/index.tpl
</code></pre>
<p>BUT Subversive won't let me commit any of the files in that folder.
The message it gives me is: </p>
<blockquote>
<p>"You are going to modify the tag on
the repository. Do you want to
continue?"</p>
</blockquote>
<p>So I say "no".
It seems to be confusing my 'tags' folder with SVN's concept of tags.</p>
<p>I can't rename the folder because the framework I'm using enforces strict naming conventions between controller & view. I have a tagsController, so my views must be in /views/tags</p>
<p>I could rename the controller to something other than 'tags', but that sucks, because a tag is a tag, not a schmag ;)</p>
<p>Any ideas on how to get around this?</p>
|
<p>It's actually fine to say "Yes" to this warning.</p>
<p>A common layout for version control is to have 3 root folders:</p>
<blockquote>
<pre><code>/trunk
/tags
/branches
</code></pre>
</blockquote>
<p>Once a trunk build has been released, the current contents of trunk are copied into a folder (e.g. "April 2008 version 1.3" or something) in tags. Generally speaking this folder should not then be modified, as it represents a specific build at a specific point in time, so Subversion will warn you if you attempt to change files in it.</p>
<p>However, in your case you have a folder which just happens to be called "tags", and contains trunk code, rather than tagged code, so it is perfectly right to say "Yes" to this warning and continue with the commit. </p>
<p>For more info, read the SVN Book, particularly <a href="http://svnbook.red-bean.com/en/1.5/svn.branchmerge.tags.html" rel="noreferrer">Tags</a> and <a href="http://svnbook.red-bean.com/en/1.5/svn.tour.importing.html#svn.tour.importing.layout" rel="noreferrer">Recommended Repository Layout</a></p>
|
<p>The <strong>trunk</strong> should usually represent the current working copy of your application, <strong>branches</strong> are there to support working on a previous version of an application (like they do with Firefox for example, they still release bug fixes to version 2.0 while the last version is in the trunk. <strong>Tags</strong> are just used to mark a specific release of your application, this makes it handy to check how code was at a specific release.</p>
<p>Why are you trying to change the tagged files?</p>
| 49,031
|
<p>I'm trying to write an app using Ruby on Rails and I'm trying to achieve the following:</p>
<blockquote>
<p>The app needs to receive UDP messages coming in on a specific port (possibly 1 or more per second) and store them in the database so that the rest of my Rails app can access it. </p>
</blockquote>
<p>I was thinking of writing a separate daemon that would receive these messages and shell out to a ruby script on my rails app that will store the message in the database using the right model. The problem with this approach is that the ruby script will be run very often. It would be better performance-wise if I could just have a long-running ruby process that can constantly receive the UDP messages store them in the database. </p>
<p>Is this the right way to do it? Is there something in the Rails framework that can help with this?</p>
|
<p>You definitely don't want to load the Rails stack for each incoming request -- that would be way too slow; you'll want to use something lower-level to handle the incoming connections. You might look at the internals of Webrick to see a simple server daemon coded in ruby -- or, if you want something more performant, look at Mongrel or Thin.</p>
<p>In general, the whole Rails stack isn't gonna help you a lot here -- most of it is geared towards serving web apps, not saving stuff straight off the wire.</p>
<p>The part of Rails that will probably help you the most is ActiveRecord -- there's a pretty good chance you'll want to use that to store your Model data in the database. In fact, you should be able to <code>include</code> your actual Rails models and use them in your UDP-monitoring process. Check the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html" rel="nofollow noreferrer">ActiveRecord docs</a> for examples in connecting to a database outside your Rails project.</p>
|
<p>I have an application that does something similar to this, i.e receiving lots of messages on a port and persisting them to the database. We addressed a number of issues when evolving the design of our database, including the fact that we must not lose messages even if the database was unavailable for some reason.</p>
<p>For performance reasons and to ensure we did not lose messages we went for a two stage process. We wrote a small handler that listened for messages and then persisted them to a message queue using <a href="http://activemq.apache.org/" rel="nofollow noreferrer">Apache Active-MQ</a>. We then used the <a href="http://code.google.com/p/activemessaging/wiki/ActiveMessaging" rel="nofollow noreferrer">ActiveMessaging</a> plugin within a separate rails application to consume the messages from the queue and persist them to the database. This method makes it easy to scale the listeners and will result in a much higher messaging throughput.</p>
<p>If you were to go this route then you might want to look at the <a href="http://fusesource.com/products/enterprise-activemq/" rel="nofollow noreferrer">Fuse implementation</a> of Active-MQ which is generally a few versions further on that the Apache version.</p>
| 15,214
|
<p>For my application, I want a <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html" rel="nofollow noreferrer">Combo Box</a> that displays its elements when dropped down as a <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html" rel="nofollow noreferrer">Tree</a>. Problem is, I'm not versed well enough in Swing to know how to go about doing this. At least without ending up writing a new widget from scratch, or something to that effect.</p>
<p>How would I do something like this without creating one from scratch?</p>
|
<p>I think I would implement this as a JTree component in a JViewPort, followed by an expansion button. When collapsed, it would look like a combo box. When you click the expansion button, the viewport would expand, allowing you to scroll and select a node in the JTree. When you selected the node, the view port would collapse back to only show the selected node and the expansion button.</p>
|
<p>Override the getListCellRendererComponent methode and create the components in level order.
For every tree level move the painted string 3 spaces to right.</p>
<p>Example:</p>
<p>1</p>
<p>. a</p>
<p>. b</p>
<p>2</p>
<p>. c</p>
<p>The original implementation you can look from</p>
<pre><code>public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//Get the selected index. (The index param isn't
//always valid, so just use the value.)
int selectedIndex = ((Integer)value).intValue();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
//Set the icon and text. If icon was null, say so.
ImageIcon icon = images[selectedIndex];
String pet = petStrings[selectedIndex];
setIcon(icon);
if (icon != null) {
setText(pet);
setFont(list.getFont());
} else {
setUhOhText(pet + " (no image available)",
list.getFont());
}
return this;
}
</code></pre>
| 46,648
|
<p>I'm concerned that this might be working on an NP-Complete problem. I'm hoping someone can give me an answer as to whether it is or not. And I'm looking for more of an answer than just yes or no. I'd like to know why. If you can say,"This is basically this problem 'x' which is/is not NP-Complete. (wikipedia link)"</p>
<p>(No this is not homework)</p>
<p>Is there a way to determine if two points are connected on an arbitrary non-directed graph. e.g., the following</p>
<pre><code>Well
|
|
A
|
+--B--+--C--+--D--+
| | | |
| | | |
E F G H
| | | |
| | | |
+--J--+--K--+--L--+
|
|
M
|
|
House
</code></pre>
<p>Points A though M (no 'I') are control points (like a valve in a natural gas pipe) that can be either open or closed. The '+'s are nodes (like pipe T's), and I guess the Well and the House are also nodes as well.</p>
<p>I'd like to know if I shut an arbitrary control point (e.g., C) whether the Well and House are still connected (other control points may also be closed). E.g., if B, K and D are closed, we still have a path through A-E-J-F-C-G-L-M, and closing C will disconnect the Well and the House. Of course; if just D was closed, closing only C does not disconnect the House.</p>
<p>Another way of putting this, is C a bridge/cut edge/isthmus?</p>
<p>I could treat each control point as a weight on the graph (either 0 for open or 1 for closed); and then find the shortest path between Well and House (a result >= 1 would indicate that they were disconnected. There's various ways I can short circuit the algorithm for finding the shortest path too (e.g., discard a path once it reaches 1, stop searching once we have ANY path that connects the Well and the House, etc.). And of course, I can also put in some artificial limit on how many hops to check before giving up.</p>
<p>Someone must have classified this kind of problem before, I'm just missing the name.</p>
|
<p>Your description seems to indicate that you are just interested in whether two nodes are connected, not finding the shortest path.</p>
<p>Finding if two nodes are connected is relatively easy:</p>
<pre><code>Create two sets of nodes: toDoSet and doneSet
Add the source node to the toDoSet
while (toDoSet is not empty) {
Remove the first element from toDoSet
Add it to doneSet
foreach (node reachable from the removed node) {
if (the node equals the destination node) {
return success
}
if (the node is not in doneSet) {
add it to toDoSet
}
}
}
return failure.
</code></pre>
<p>If you use a hash table or something similar for toDoSet and doneSet, I believe this is a linear algorithm.</p>
<p>Note that this algorithm is basically the mark portion of mark-and-sweep garbage collection.</p>
|
<p>Any graph shortest path algorithm will be overkill if all you need is to find if a node is connected to another. A good Java library that accomplishes that is <a href="http://jgrapht.org/" rel="nofollow noreferrer">JGraphT</a>. It's usage is quite simple, here's an example of an Integer graph:</p>
<pre><code>public void loadGraph() {
// first we create a new undirected graph of Integers
UndirectedGraph<Integer, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);
// then we add some nodes
graph.addVertex(1);
graph.addVertex(2);
graph.addVertex(3);
graph.addVertex(4);
graph.addVertex(5);
graph.addVertex(6);
graph.addVertex(7);
graph.addVertex(8);
graph.addVertex(9);
graph.addVertex(10);
graph.addVertex(11);
graph.addVertex(12);
graph.addVertex(13);
graph.addVertex(14);
graph.addVertex(15);
graph.addVertex(16);
// then we connect the nodes
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(3, 5);
graph.addEdge(5, 6);
graph.addEdge(6, 7);
graph.addEdge(7, 8);
graph.addEdge(8, 9);
graph.addEdge(9, 10);
graph.addEdge(10, 11);
graph.addEdge(11, 12);
graph.addEdge(13, 14);
graph.addEdge(14, 15);
graph.addEdge(15, 16);
// finally we use ConnectivityInspector to check nodes connectivity
ConnectivityInspector<Integer, DefaultEdge> inspector = new ConnectivityInspector<>(graph);
debug(inspector, 1, 2);
debug(inspector, 1, 4);
debug(inspector, 1, 3);
debug(inspector, 1, 12);
debug(inspector, 16, 5);
}
private void debug(ConnectivityInspector<Integer, DefaultEdge> inspector, Integer n1, Integer n2) {
System.out.println(String.format("are [%s] and [%s] connected? [%s]", n1, n2, inspector.pathExists(n1, n2)));
}
</code></pre>
<p>This lib also offers all the shortest paths algorithms as well.</p>
| 46,159
|
<p>I have a table that represents a series of matches between ids from another table as follows:</p>
<pre><code>CREATE TABLE #matches (
asid1 int,
asid2 int
)
insert into #matches values (1,2)
insert into #matches values (1,3)
insert into #matches values (3,1)
insert into #matches values (3,4)
insert into #matches values (7,6)
insert into #matches values (5,7)
insert into #matches values (8,1)
insert into #matches values (1,8)
insert into #matches values (8,9)
insert into #matches values (8,3)
insert into #matches values (10,11)
insert into #matches values (12,10)
</code></pre>
<p>and I want to find groups of matches that are linked directly or indirectly to one another.</p>
<p>The output would look like this:</p>
<pre><code>group asid
1 1
1 2
1 3
1 4
1 8
1 9
2 5
2 6
2 7
3 10
3 11
3 12
</code></pre>
<p>if I were to add another row:</p>
<pre><code>insert into #matches values (7,8)
</code></pre>
<p>then this would mean that 2 of the groups above would be linked, so I would require output:</p>
<pre><code>group asid
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
2 10
2 11
2 12
</code></pre>
<p>Any ideas?</p>
<p>Edit: Further research leads me to believe that a recursive common table expression should do the trick... if I figure out something elegant I'll post it</p>
|
<p>It appears that a <a href="http://en.wikipedia.org/wiki/Disjoint-set_data_structure" rel="nofollow noreferrer">Disjoint-set</a> is what you need to solve this. Here is a <a href="http://www.emilstefanov.net/Programming/DisjointSets.aspx" rel="nofollow noreferrer">listing</a> of a C# and C++ implementation.</p>
|
<p>If this can be done at all within SQL, it's going to be insanely difficult. You should analyze that table in whatever programming language you're using.</p>
| 49,955
|
<p>An interesting problem that no doubt someone here has come across before. </p>
<p>I'm reading a CSV file that contains some values wrapped in quotes, I came across a problem today were my app couldn't read the file as the value was wrapped in cury quotation marks and not square quotation marks. Is this an encoding problem? I simply replaced the quotes replacing curly quote with ".</p>
<p>Can someone explain why this happens and what I can do about it? I'm using C#</p>
|
<p>I suspect the data was copied and pasted from a document created using Word.</p>
<p>By default Word 2003 will convert "straight quotes" to what it calls “smart quotes”. You can override this behavior using Tools/AutoCorrect Options/AutoFormat as you type.</p>
|
<p>I suspect the data was copied and pasted from a document created using Word.</p>
<p>By default Word 2003 will convert "straight quotes" to what it calls “smart quotes”. You can override this behavior using Tools/AutoCorrect Options/AutoFormat as you type.</p>
| 43,317
|
<p>I am redesigning a command line application and am looking for a way to make its use more intuitive. Are there any conventions for the format of parameters passed into a command line application? Or any other method that people have found useful?</p>
|
<p>I see a lot of Windows command line specifics, but if your program is intended for Linux, I find the <a href="http://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html" rel="noreferrer">GNU command line standard</a> to be the most intuitive. Basically, it uses double hyphens for the long form of a command (e.g., <code>--help</code>) and a single hyphen for the short version (e.g., <code>-h</code>). You can also "stack" the short versions together (e.g., <code>tar -zxvf</code> <em><code>filename</code></em>) and mix 'n match long and short to your heart's content.</p>
<p>The GNU site also lists <a href="http://www.gnu.org/prep/standards/html_node/Option-Table.html#Option-Table" rel="noreferrer">standard option names</a>.</p>
<p>The <a href="http://www.gnu.org/software/libc/manual/html_node/Getopt.html" rel="noreferrer">getopt library</a> greatly simplifies parsing these commands. If C's not your bag, <a href="http://docs.python.org/lib/module-getopt.html" rel="noreferrer">Python</a> has a similar library, as does <a href="http://aplawrence.com/Unix/perlgetopts.html" rel="noreferrer">Perl</a>.</p>
|
<p>-operation [parameters] -command [your command] -anotherthings [otherparams]....</p>
<p>For example,</p>
<pre><code>YourApp.exe -file %YourProject.prj% -Secure true
</code></pre>
| 13,407
|
<p>There seems to be lots of different ways to register assemblies with the GAC, as in, they 'work'. However, what's the "proper" way of doing it?</p>
<p>In response to Lou Franco (and gacutil):</p>
<p>I'm using Gacutil for development, but it seems to me to be not the proper way to install it, since gacutil isn't included in the basic .NET utilities past .NET 1.1 - it's only a developer tool.</p>
<p>Additional: Gacutil (as seen in responses below) is not redistributable, and therefore should not be used in any app that you intend to give to people who are not developers. AKA, customers. See <a href="http://blogs.msdn.com/astebner/archive/2006/11/04/why-to-not-use-gacutil-exe-in-an-application-setup.aspx" rel="noreferrer">This blog post (and comments) by Aaron Stebner</a>.</p>
<p>In response to using WIX:</p>
<p>WIX might be great and all, but how does it work under the hood? What details makes the way WIX installs the assembly the right way to install it? How does it look it up? Is it a system/.NET call? Is there some call in a dll buried somewhere in System32 that needs to be made? </p>
<p>(Edit: it looks like WIX uses MSI under the hood. See my comments in the accepted answer.)</p>
<p>Final edit: It looks like the correct way to install an assembly to the GAC is using windows installer, and nothing else. I'm going to give Wix a try. Thanks all!</p>
|
<p>With Wix I would do something like this:</p>
<pre>
<DirectoryRef Id="MyDirectory" >
<Component Id="MyComponent" Guid="PUT-GUID-HERE" DiskId="1">
<File Id="MyAssembly" Name="MyAssembly.dll" Assembly=".net" KeyPath="yes" Source="MyAssembly.dll" />
</Component>
</DirectoryRef>
</pre>
<p>When you use the attribute Assembly=".net" for a file in WiX, it will create entries in the MsiAssembly and MsiAssemblyName table for this component and mark it as a GAC component.</p>
|
<p>copy directly to %WINDIR%\Assembly.</p>
<p>Advantage: Straightforward.</p>
<p>Disadvantage: AFAIK, %WINDIR%\Assembly just <em>happens</em> to be where it is right now, and it's location is subject to change. This would make it break in future versions of windows or if that folder's behavior chaneges. This probably isn't the right way.</p>
<p>Extreme Disadvantage: As said by madmath:</p>
<blockquote>just copying your assembly into c:\windows\assembly won't work. Explorer only shows a simplified view of the folder, which contains in fact lots of different folders for different kinds of assemblies. Doing a copy in it from an installer won't trigger all the operations done by explorer on a drag-and-drop. (written here because I don't have enough reputation yet to comment on other posts).</blockquote>
| 25,139
|
<p>I am trying to encode/decode MIME headers in Ruby.</p>
|
<p>Ruby has Base64 methods in core, just do</p>
<pre><code>require "base64"
</code></pre>
<p>and use <code>Base64.decode64</code> and <code>Base64.encode64</code>. For quoted-printable, you could use the following code <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/133587" rel="nofollow noreferrer">here</a>.</p>
|
<p>If the mime content is related to emails you might also want to check out TMAil...</p>
<p><a href="http://tmail.rubyforge.org/" rel="nofollow noreferrer">http://tmail.rubyforge.org/</a></p>
<p>It has a nice approach to parsing out email attachments and multi-part messages and what not.</p>
| 48,793
|
<p>ToolStrip with MenuStrip or RibbonBar? </p>
<hr>
<p>It combines both of the controls. It also have a TabPages navigation, contextual tabs, etc. However the RibbonBar is a very complex control and when you open a new document in for example Word2007 the half of the screen you see a Ribbon Bar. It is not cool. When you have toolStrips you can layout them to Top, Bottom, Left, Right and have more control of the UI look. We can also hide the toolstrips which we do not want to see and they no longer take any screen space. </p>
|
<p>Ribbon Bar</p>
|
<p>It boils down to what you're trying to navigate and how complex do you want the Navigation to work.</p>
<p>I prefer to use simple existing applications to base my programs.</p>
<p>Thus for the most part I use either the MenuStrip + X ToolStrips or just a simple ToolStrip if a menu is more involved than is required to get a task done.</p>
<p>But I would have to guess that many people like the Ribbon Bar since it combines the functionality of both Menu and ToolStrips into one control.</p>
| 24,028
|
<p>What won't plugins wont work with vb c# studio express?</p>
|
<p>The Express editions do not support Visual Studio Addins.</p>
|
<p>Students qualify for <a href="https://downloads.channel8.msdn.com/" rel="nofollow noreferrer">free Microsoft software</a>, which include Visual Studio Pro.</p>
| 15,235
|
<p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html" rel="noreferrer"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
|
<p>Python 3.8 added the <a href="https://docs.python.org/3/library/datetime.html#datetime.date.fromisocalendar" rel="noreferrer">fromisocalendar()</a> method:</p>
<pre><code>>>> datetime.fromisocalendar(2011, 22, 1)
datetime.datetime(2011, 5, 30, 0, 0)
</code></pre>
<p>Python 3.6 added the <a href="https://docs.python.org/3.6/whatsnew/3.6.html#datetime" rel="noreferrer"><code>%G</code>, <code>%V</code> and <code>%u</code> directives</a>:</p>
<pre><code>>>> datetime.strptime('2011 22 1', '%G %V %u')
datetime.datetime(2011, 5, 30, 0, 0)
</code></pre>
<p><strong>Original answer</strong></p>
<p>I recently had to solve this problem myself, and came up with this solution:</p>
<pre><code>import datetime
def iso_year_start(iso_year):
"The gregorian calendar date of the first day of the given ISO year"
fourth_jan = datetime.date(iso_year, 1, 4)
delta = datetime.timedelta(fourth_jan.isoweekday()-1)
return fourth_jan - delta
def iso_to_gregorian(iso_year, iso_week, iso_day):
"Gregorian calendar date for the given ISO year, week and day"
year_start = iso_year_start(iso_year)
return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)
</code></pre>
<p>A few test cases:</p>
<pre><code>>>> iso = datetime.date(2005, 1, 1).isocalendar()
>>> iso
(2004, 53, 6)
>>> iso_to_gregorian(*iso)
datetime.date(2005, 1, 1)
>>> iso = datetime.date(2010, 1, 4).isocalendar()
>>> iso
(2010, 1, 1)
>>> iso_to_gregorian(*iso)
datetime.date(2010, 1, 4)
>>> iso = datetime.date(2010, 1, 3).isocalendar()
>>> iso
(2009, 53, 7)
>>> iso_to_gregorian(*iso)
datetime.date(2010, 1, 3)
</code></pre>
|
<p><em>EDIT: ignore this, the edge cases are a pain. Go with Ben's solution.</em></p>
<p>Ok, on closer inspection I noticed that <code>strptime</code> has <code>%W</code> and <code>%w</code> parameters, so the following works:</p>
<pre><code>def fromisocalendar(y,w,d):
return datetime.strptime( "%04dW%02d-%d"%(y,w-1,d), "%YW%W-%w")
</code></pre>
<p>A couple of gotchas: The ISO week number starts at <code>1</code>, while <code>%W</code> starts at <code>0</code>. The ISO week day starts at <code>1</code> (Monday), which is the same as <code>%w</code>, so Sunday would probably have to be <code>0</code>, not <code>7</code>...</p>
| 39,090
|
<p>I have a command that runs fine if I ssh to a machine and run it, but fails when I try to run it using a remote ssh command like : </p>
<pre><code>ssh user@IP <command>
</code></pre>
<p>Comparing the output of "env" using both methods resutls in different environments. When I manually login to the machine and run env, I get much more environment variables then when I run :</p>
<pre><code>ssh user@IP "env"
</code></pre>
<p>Any idea why ?</p>
|
<p>There are different types of shells. The SSH command execution shell is a non-interactive shell, whereas your normal shell is either a login shell or an interactive shell. Description follows, from man bash:</p>
<pre>
A login shell is one whose first character of argument
zero is a -, or one started with the --login option.
An interactive shell is one started without non-option
arguments and without the -c option whose standard input
and error are both connected to terminals (as determined
by isatty(3)), or one started with the -i option. PS1 is
set and $- includes i if bash is interactive, allowing a
shell script or a startup file to test this state.
The following paragraphs describe how bash executes its
startup files. If any of the files exist but cannot be
read, bash reports an error. Tildes are expanded in file
names as described below under Tilde Expansion in the
EXPANSION section.
When bash is invoked as an interactive login shell, or as
a non-interactive shell with the --login option, it first
reads and executes commands from the file /etc/profile, if
that file exists. After reading that file, it looks for
~/.bash_profile, ~/.bash_login, and ~/.profile, in that
order, and reads and executes commands from the first one
that exists and is readable. The --noprofile option may
be used when the shell is started to inhibit this behav
ior.
When a login shell exits, bash reads and executes commands
from the file ~/.bash_logout, if it exists.
When an interactive shell that is not a login shell is
started, bash reads and executes commands from ~/.bashrc,
if that file exists. This may be inhibited by using the
--norc option. The --rcfile file option will force bash
to read and execute commands from file instead of
~/.bashrc.
When bash is started non-interactively, to run a shell
script, for example, it looks for the variable BASH_ENV in
the environment, expands its value if it appears there,
and uses the expanded value as the name of a file to read
and execute. Bash behaves as if the following command
were executed:
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
but the value of the PATH variable is not used to search
for the file name.
</pre>
|
<p>I found an easy resolution for this issue was to add
source /etc/profile
to the top of the script.sh file I was trying to run on the target system.
On the systems here, this caused the environmental variables which were needed by script.sh to be configured as if running from a login shell.</p>
<p>In one of the prior responses it was suggested that ~/.bashr_profile etc... be used.
I didn't spend much time on this but, the problem with this is if you ssh to a different user on the target system than the shell on the source system from which you log in it appeared to me that this causes the source system user name to be used for the ~.</p>
| 26,582
|
<p>I would like to add the following MIME type to a site run by <code>Apache</code>:</p>
<pre><code><mime-mapping>
<extension>jnlp</extension>
<mime-type>application/x-java-jnlp-file</mime-type>
</mime-mapping>
</code></pre>
<p><strong>That is the Tomcat format.</strong></p>
<p>I'm on a shared host, so I can only create an <code>.htaccess</code> file. Would someone please specify the complete contents of such a file?</p>
|
<pre><code>AddType application/x-java-jnlp-file .jnlp
</code></pre>
<p>Note that you might not actually be allowed to do that.</p>
<p>See also the <a href="http://HTTPd.Apache.Org/docs/trunk/mod/mod_mime.html#addtype" rel="noreferrer" title="mod_mime - AddType">documentation of the AddType directive</a> and the <a href="http://HTTPd.Apache.Org/docs/trunk/howto/htaccess.html" rel="noreferrer" title=".htaccess howto">.htaccess howto</a>.</p>
|
<p>You should be able to just add this line:</p>
<pre><code>AddType application/x-java-jnlp-file .jnlp
</code></pre>
| 5,384
|
<p>Often I want to add a value to a table or update the value if its key already exists. This can be accomplished in several ways, assuming a primary or unique key is set on the 'user_id' and 'pref_key' columns in the example:</p>
<p><strong>1. Blind insert, update if receiving a duplicate key error:</strong></p>
<pre><code>// Try to insert as a new value
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If a duplicate-key error occurs run an update query
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
</code></pre>
<p><strong>2. Check for existence, then select or update:</strong></p>
<pre><code>// Check for existence
SELECT COUNT(*)
FROM my_prefs
WHERE user_id=1234 AND pref_key='show_help';
// If count is zero, insert
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If count is one, update
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
</code></pre>
<p>The first way seems to be preferable as it will require only one query for new inserts and two for an update, where as the second way will always require two queries. Is there anything I'm missing though that would make it a bad idea to blindly insert?</p>
|
<p>have a look at the ON DUPLICATE KEY syntax in <a href="http://dev.mysql.com/doc/refman/5.0/en/insert-select.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/insert-select.html</a></p>
<pre><code>INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
</code></pre>
|
<p>The first way is the preferred way as far as I know.</p>
| 18,048
|
<p>In Flex I'm using the following code to allow sorting in a DataGrid (the data is paged and sorted serverside).</p>
<pre>
private function headerReleaseHandler(event:DataGridEvent):void
{
var column:DataGridColumn = DataGridColumn(event.currentTarget.columns[event.columnIndex]);
if(this.count>0)
{
if(this.query.SortField == column.dataField)
{
this.query.SortAscending = !this.query.SortAscending;
}
else
{
this.query.SortField = column.dataField;
this.query.SortAscending = true;
}
this.fill();
}
event.preventDefault();
}
</pre>
<p>This works perfectly, except that the arrows that indicate sorting isn't shown. How can I accomplish that?</p>
<p>Thanks!
/Niels </p>
|
<p>There is an example here if this is what you are looking for:
<a href="http://blog.flexexamples.com/2008/02/28/displaying-the-sort-arrow-in-a-flex-datagrid-control-without-having-to-click-a-column/" rel="noreferrer">http://blog.flexexamples.com/2008/02/28/displaying-the-sort-arrow-in-a-flex-datagrid-control-without-having-to-click-a-column/</a></p>
<p>It looks like you need to refresh the collection used by your dataprovider.</p>
|
<p>in the above code what does "this" refer to is it the datagrid because I am confused by this.query.SortField , I am assuming 'this' and "query' are your own custom objects. and why are you checking for count. what count is that.</p>
<p>Regards
-Mohan</p>
| 41,821
|
<p>Jeff mentioned the concept of 'Progressive Enhancement' when talking about using JQuery to write stackoverflow.</p>
<p>After a quick Google, I found a couple of high-level discussions about it.</p>
<p>Can anyone recommend a good place to start as a programmer.</p>
<p>Specifically, I have been writing web apps in PHP and would like to use YUI to improve the pages I am writing, but a lot of them seem very JavaScript based, with most of the donkey work being done using JavaScript. To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it.</p>
<p>Anyone have some good places to start using this idea, I don't really care about the language.</p>
<p>Ideally, I would like to see how you start creating the static HTML first, and then adding the YUI (or whatever Ajax framework) to it so that you get the benefits of a richer client?</p>
|
<p>As you've said</p>
<blockquote>
<p>To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it.</p>
</blockquote>
<p>This isn't progressive enhancement. Progressive enhancement is when the site works perfectly without JavaScript or CSS, and <em>then</em> adding (layering) these extra technologies/code to increase the usability and functionality of the website.</p>
<p>The best example I can give is the tag input box on this website. With JavaScript turned off, it would still work allowing you to enter tags separated with a space. With JavaScript turned on, you get a drop down with suggestions of previous entries.</p>
<p>This is progressive enhancement.</p>
|
<p>Going at it from the other direction is sometimes referred to as graceful degradation. This is usually needed when the site is built first with the enhanced functionality afforded by the various technologies then modified to degrade gracefully for browsers with those technologies are not available.</p>
<p>It is also graceful degradation when designing to work with older browsers (ancient in the Internets terminology) such as IE 5.5, Netscape, etc...</p>
<p>In my opinion it is much more work to gracefully degrade the application. Progressively enhancing it tends to be much more efficient; however, sometimes the need to take an existing app and make it accessible in these lacking environments arise.</p>
| 2,459
|
<p>Wanted to convert</p>
<pre><code><br/>
<br/>
<br/>
<br/>
<br/>
</code></pre>
<p>into</p>
<pre><code><br/>
</code></pre>
|
<p>You can do this with a regular expression:</p>
<pre><code>preg_replace("/(<br\s*\/?>\s*)+/", "<br/>", $input);
</code></pre>
<p>This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.</p>
|
<p>You probably want to use a Regular Expression. I haven't tested the following, but I believe it's right. </p>
<pre><code>$text = preg_replace( "/(<br\s?\/?>)+/i","<br />", $text );
</code></pre>
| 16,168
|
<p>Kind of a basic question but I'm having troubles thinking of a solution so I need a push in the right direction.</p>
<p>I have an input file that I'm pulling in, and I have to put it into one string variable. The problem is I need to split this string up into different things. There will be 3 strings and 1 int. They are separated by a ":".</p>
<p>I know I can find the position of the first ":" by find(), but I really don't know how to progress through the string, for each thing and put it into it's own string / int.</p>
<p>The actual input from the file looks something like this:</p>
<pre><code>A:PEP:909:Inventory Item
</code></pre>
<p>A is going to be command I have to execute... so that will be a string.
PEP is a key, needs to be a string.
909 is an int.</p>
<p>and the last is a string.</p>
<p>So what I think I want to do is have 3 string var's, and 1 int and get all those things put into their respective variables. </p>
<p>So I think I'll end up wanting to conver this C++ string to a C string so I can use atoi to convert the one section to an int.</p>
|
<p>I usually use something like this:</p>
<pre><code>void split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
</code></pre>
<p>you can use it like this:</p>
<pre><code>std::vector<std::string> tokens;
split("this:is:a:test", ':', tokens);
</code></pre>
<p>tokens will now contain "this", "is", "a", and "test"</p>
|
<p>A comfortable solution that I found is not uncommon is the following prototype:</p>
<pre><code>string SplitToken(string & body, char separator)
</code></pre>
<p>which returnsd everything up to the first occurence of separator, and removes that part including the separator. </p>
<p>"My" MFC - CString-based implementation looks as follows:</p>
<pre><code>CString SplitStringAt(CString & s, int idx)
{
CString ret;
if (idx < 0)
{
ret = s;
s.Empty();
}
else
{
ret = s.Left(idx);
s = s.Mid(idx+1);
}
return ret;
}
CString SplitToken(CString & s,TCHAR separator)
{
return SplitStringAt(s, s.Find(separator));
}
</code></pre>
<p>This is definitely not the most efficient method - the major drawback is that body is modified and a new (partial) copy is made for every token, so don't use it in performance-critical location! </p>
<p>However, I found this (and a few related functions) immensely useful, for simple parsers.</p>
| 42,066
|
<pre><code>abstract class Foo
{
private List<Object> container;
private bool update;
Foo Foo()
{
container = new List<object>();
update = false;
}
public abstract Bar CreateBar();
public void BeginUpdate()
{
if (!update)
{
Thread update_thread = new Thread(new ThreadStart(Update));
update_thread.Start();
}
}
private void Update()
{
update = true;
while (update)
{
lock (container)
{
if (...)
container.Add(this.CreateBar());
else
container.Remove(...);
}
Thread.Sleep(1337);
}
}
public void EndUpdate()
{
update = false;
}
public List<Object> Objects
{
get
{
lock (container)
{
return this.container;
}
}
}
}
</code></pre>
<p>When something outside of Foo calls the Foo's Object accessor like,</p>
<pre><code>List<Objects> objects = foo_instance.Objects;
foreach (Object o in objects)
{
Thread.Sleep(31173);
}
</code></pre>
<p>How will the locking occur? Will the thread running Update() have to wait until the above foreach is done processing objects list? I would like that these two would work simultaneously, is the only solution to make a deep copy of objects?</p>
|
<p>Your code does not do what you think it does. This method</p>
<pre><code>public List<Object> Objects
{
get
{
lock (container)
{
return this.container;
}
}
}
</code></pre>
<p>Does not hold the lock after it has returned the value. So your loop is not locked.</p>
<p>You cannot return the container instance from the clas</p>
|
<p>krosenvald is correct, the lock on the Objects accessor is released as soon as the property returns the pointer to the container object... </p>
<p>In you code</p>
<pre><code>List<Objects> objects = foo_instance.Objects;
foreach (Object o in objects)
{
Thread.Sleep(31173);
}
</code></pre>
<p>The lock only lasts for the first line... where the reference variable "objects" is being populated... There's really no need to lock anything for that line since no memory is being modified by fetching the pointer... </p>
| 42,276
|
<p>I have a class which constructor takes a <a href="http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/enums/Enum.html" rel="nofollow noreferrer">Jakarta enums</a>. I'm trying to find how I can easily inject it via an <a href="http://www.springframework.org/" rel="nofollow noreferrer">Spring</a> XML aplicationContext.</p>
<p>For example :</p>
<p>The enum :</p>
<pre><code>public class MyEnum extends org.apache.commons.lang.enums.Enum {
public static final MyEnum MY_FIRST_VALUE = new MyEnum("MyFirstValue");
public static final MyEnum MY_SECOND_VALUE = new MyEnum("MySecondValue");
public static MyEnum getEnum(String name) {
return (MyEnum) getEnum(MyEnum.class, name);
}
[...other standard enum methods]
}
</code></pre>
<p>The class in which to inject :</p>
<pre><code>public class MyService {
private final MyEnum status;
public MyService(MyEnum status) {
this.status = status;
}
}
</code></pre>
<p>The application context :</p>
<pre><code><bean id="myService" class="MyService">
<constructor-arg index="0" value="MyFirstValue" />
</bean>
</code></pre>
<p>Of course, with this I have a <code>no matching editors or conversion strategy found</code> error. Is there an easy integration between Spring and the Jakarta enums ? Or should I write my own PropertyEditor ?</p>
|
<p>Check out the <code><util:constant></code> tag in Spring. It will require you to add the schema to your xml definition. So you would wind up with the following:</p>
<pre><code><bean id="myService" class="MyService">
<constructor-arg index="0">
<util:constant static-field="MyEnum.MY_FIRST_VALUE"/>
</constructor-arg>
</bean>
</code></pre>
<p>The definition and usage of the tag (including the XSD def) is found <a href="http://static.springframework.org/spring/docs/2.5.x/reference/xsd-config.html#xsd-config-body-schemas-util" rel="nofollow noreferrer">here</a>.</p>
|
<p>I voted-up Spencer's answer but found that this will work as well. In this example, you just need to specify the <strong>index, type</strong>, and <strong>name</strong> in the constructor-arg.</p>
<pre><code><bean id="myService" class="MyService">
<constructor-arg index="0" type="com.package.MyEnum" value="MyFirstValue" />
</bean>
</code></pre>
<p>I based this off of an error message I received:</p>
<blockquote>
<p><em>(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)</em></p>
</blockquote>
| 40,610
|
<p>I want to get the size of a drive (or UNC path pointing to a partition would be nice, but not required), as well as free space for said drive (or UNC path). This doesn't need to work cross platform; only in Windows.</p>
<p>I know it's easy to do in Java 6, but that's not an option; I'm stuck with Java 5.</p>
<p>I can get the free space available by doing:</p>
<blockquote>
<p>cmd.exe /c Z:\ /-c</p>
<p>or</p>
<p>cmd.exe /c \\server\share /-c</p>
</blockquote>
<p>and just parsing out the resulting bytes free. However I can't seem to find a way to get the total drive size.</p>
<p>Any suggestions?</p>
|
<p>One way to do it would be to use fsutil on the command line. It returns something like this:</p>
<pre><code>D:\>fsutil fsinfo ntfsinfo c:
NTFS Volume Serial Number : 0xd49cf9cf9cf9ac5c
Version : 3.1
Number Sectors : 0x0000000004a813ff
Total Clusters : 0x000000000095027f
Free Clusters : 0x00000000002392f5
Total Reserved : 0x0000000000000490
Bytes Per Sector : 512
Bytes Per Cluster : 4096
Bytes Per FileRecord Segment : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length : 0x000000000e70c000
Mft Start Lcn : 0x00000000000c0000
Mft2 Start Lcn : 0x0000000000000010
Mft Zone Start : 0x0000000000624ea0
Mft Zone End : 0x0000000000643da0
</code></pre>
<p>Multipy your number of sectors times the bytes per sector to get your size.</p>
|
<p>You could use the <a href="http://support.hyperic.com/display/SIGAR/Home" rel="nofollow noreferrer">SIGAR</a> library, which gives you native access on many platforms.</p>
| 31,294
|
<p>Which C#/.NET Dependency Injection frameworks are worth looking into?
And what can you say about their complexity and speed.</p>
|
<p><strong>edit</strong> (not by the author): There is a comprehensive list of IoC frameworks available at <a href="https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc" rel="nofollow noreferrer">https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc</a>:</p>
<ul>
<li><a href="https://github.com/castleproject/Windsor" rel="nofollow noreferrer">Castle Windsor</a> - Castle Windsor is best of breed, mature Inversion of Control container available for .NET and Silverlight</li>
<li><a href="https://github.com/unitycontainer/unity" rel="nofollow noreferrer">Unity</a> - Lightweight extensible dependency injection container with support for constructor, property, and method call injection</li>
<li><a href="https://github.com/autofac/Autofac" rel="nofollow noreferrer">Autofac</a> - An addictive .NET IoC container</li>
<li><a href="https://github.com/dadhi/DryIoc" rel="nofollow noreferrer">DryIoc</a> - Simple, fast all fully featured IoC container.</li>
<li><a href="https://github.com/ninject/ninject" rel="nofollow noreferrer">Ninject</a> - The ninja of .NET dependency injectors</li>
<li><a href="https://github.com/spring-projects/spring-net" rel="nofollow noreferrer">Spring.Net</a> - Spring.NET is an open source application framework that makes building enterprise .NET applications easier</li>
<li><a href="https://jasperfx.github.io/lamar/" rel="nofollow noreferrer">Lamar</a> - A fast IoC container heavily optimized for usage within ASP.NET Core and other .NET server side applications.</li>
<li><a href="https://github.com/seesharper/LightInject" rel="nofollow noreferrer">LightInject</a> - A ultra lightweight IoC container</li>
<li><a href="https://github.com/simpleinjector/SimpleInjector" rel="nofollow noreferrer">Simple Injector</a> - Simple Injector is an easy-to-use Dependency Injection (DI) library for .NET 4+ that supports Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono.</li>
<li><a href="https://github.com/aspnet/DependencyInjection" rel="nofollow noreferrer">Microsoft.Extensions.DependencyInjection</a> - The default IoC container for ASP.NET Core applications.</li>
<li><a href="https://github.com/khellang/Scrutor" rel="nofollow noreferrer">Scrutor</a> - Assembly scanning extensions for Microsoft.Extensions.DependencyInjection.</li>
<li><a href="https://github.com/Microsoft/vs-mef" rel="nofollow noreferrer">VS MEF</a> - Managed Extensibility Framework (MEF) implementation used by Visual Studio.</li>
<li><a href="https://github.com/grumpydev/TinyIoC" rel="nofollow noreferrer">TinyIoC</a> - An easy to use, hassle free, Inversion of Control Container for small projects, libraries and beginners alike.</li>
<li><a href="https://github.com/z4kn4fein/stashbox" rel="nofollow noreferrer">Stashbox</a> - A lightweight, fast and portable dependency injection framework for .NET based solutions.</li>
</ul>
<p>Original answer follows.</p>
<hr />
<p>I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI.</p>
<p>That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use <a href="http://www.springframework.net/" rel="nofollow noreferrer">Spring.Net</a> and <a href="https://github.com/castleproject/Windsor/blob/master/docs/README.md" rel="nofollow noreferrer">CastleWindsor</a> a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using <a href="http://structuremap.github.io/" rel="nofollow noreferrer">StructureMap</a> for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day.</p>
<p><strong>Update</strong></p>
<p>I've been using <a href="http://ninject.org/" rel="nofollow noreferrer">Ninject</a> on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a <a href="http://www.dimecasts.net/Casts/ByAuthor/Justin%20Etheredge" rel="nofollow noreferrer">fantastic set of Ninject screencasts</a> by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of <a href="http://structuremap.github.io/" rel="nofollow noreferrer">StructureMap</a> in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there.</p>
<p>Other IoC screencasts can also be found <a href="http://www.dimecasts.net/Casts/ByTag/IoC" rel="nofollow noreferrer">here on Dimecasts</a>.</p>
|
<p>I've used <a href="http://www.springframework.net/" rel="nofollow noreferrer">Spring.NET</a> in the past and had great success with it. I never noticed any substantial overhead with it, though the project we used it on was fairly heavy on its own. It only took a little time reading through the <a href="http://www.springframework.net/documentation.html#Reference_Manual_and_API" rel="nofollow noreferrer">documentation</a> to get it set up.</p>
| 4,152
|
<p>By "code snippet execution", I mean the ability to write a few lines of code, run and test it without having to fire up an IDE and create a dummy project.</p>
<p>It's incredibly useful for helping people with a small code sample without creating a project, compiling everything cleanly, sending them the code snippet and deleting the project. </p>
<p>I'm not asking about the best code snippets or a snippet editor or where to store snippets!</p>
<p>For C#, I use <a href="http://www.sliver.com/dotnet/SnippetCompiler/" rel="noreferrer">Snippet Compiler</a>.</p>
<p>For Java, I use Eclipse <a href="http://www.eclipsezone.com/eclipse/forums/t61137.html" rel="noreferrer">Scrapbook</a>. </p>
<p>For LINQ, I use <a href="http://www.linqpad.net/" rel="noreferrer">LINQPad</a>. </p>
<p>Any suggestions for other (better?) tools? e.g. is there one for Java that doesn't involve firing up Eclipse?</p>
<p>What about C?</p>
|
<p>For C, the in-browser <a href="http://codepad.org/" rel="nofollow noreferrer">http://codepad.org/</a> is truly excellent. Executes code and everything.</p>
|
<p>In Ruby you can use the <a href="http://en.wikipedia.org/wiki/Interactive_Ruby_Shell" rel="nofollow noreferrer">Interactive Ruby Shell</a>.</p>
<p>It also looks like the guru's at the mono project have gone and made a <a href="http://www.mono-project.com/CsharpRepl" rel="nofollow noreferrer">C# interactive</a>. YAY</p>
| 33,066
|
<p>Is there a better/simpler way to find the number of images in a directory and output them to a variable?</p>
<pre><code>function dirCount($dir) {
$x = 0;
while (($file = readdir($dir)) !== false) {
if (isImage($file)) {$x = $x + 1}
}
return $x;
}
</code></pre>
<p>This seems like such a long way of doing this, is there no simpler way?</p>
<p><strong>Note:</strong> The isImage() function returns true if the file is an image.</p>
|
<p>Check out the Standard PHP Library (aka SPL) for DirectoryIterator:</p>
<pre><code>$dir = new DirectoryIterator('/path/to/dir');
foreach($dir as $file ){
$x += (isImage($file)) ? 1 : 0;
}
</code></pre>
<p>(FYI there is an undocumented function called iterator_count() but probably best not to rely on it for now I would imagine. And you'd need to filter out unseen stuff like . and .. anyway.)</p>
|
<p>Your answer seems about as simple as you can get it. I can't think of a shorter way to it in either PHP or Perl.</p>
<p>You might be able to a system / exec command involving ls, wc, and grep if you are using Linux depending how complex isImage() is.</p>
<p>Regardless, I think what you have is quite sufficient. You only have to write the function once.</p>
| 27,721
|
<p>I need to get the "td" element of a table. I do not have the ability to add a mouseover or onclick event to the "td" element, so I need to add them with JQUERY.</p>
<p>I need JQUERY to add the mouseover and onclick event to the all "td" elements in the table.</p>
<p>Thats what I need, maybe someone can help me out? </p>
|
<pre><code>$(function() {
$("table#mytable td").mouseover(function() {
//The onmouseover code
}).click(function() {
//The onclick code
});
});
</code></pre>
|
<p>Work off of the following code to get you started. It should do just what you need. </p>
<pre><code>$("td").hover(function(){
$(this).css("background","#0000ff");
},
function(){
$(this).css("background","#ffffff");
});
</code></pre>
<p>You can use <a href="http://www.ibm.com/developerworks/web/library/wa-jquery2/" rel="nofollow noreferrer">this as a reference, which is where I pulled that code</a>.</p>
| 19,409
|
<p>I find that most books concerning C++ templates don't tell anything about whether it's possible or not to use initialization list in constructor of a template class.</p>
<p>For example, I have code like this:</p>
<pre><code>template <class T>
class Stack {
T* data;
std::size_t count;
std::size_t capacity;
enum {INIT = 5};
public:
Stack() {
count = 0;
capacity = INIT;
data = new T [INIT];
}
</code></pre>
<p>Can I replace the constructor with</p>
<pre><code>Stack(): count(0), capacity(INIT), data(new T [INIT])
</code></pre>
|
<p>Yes. Did the compiler tell you otherwise?</p>
|
<p>I've just tried and VS2008 says that it's OK, but it seems a little bit strange because some great authors don't do that (Eckel, for example, in his "Thinking in C++").</p>
| 28,568
|
<p>My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory.</p>
<p>Is there a way to tell the runtime that the dlls are in a seperate subfolder?</p>
|
<p>One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event.</p>
<pre><code>AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
</code></pre>
<p>Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method.</p>
<p>EDIT:</p>
<p>Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool.</p>
|
<p>You can use the <code><codeBase></code> element found in the application configuration file. More information on "<a href="http://msdn.microsoft.com/en-us/library/15hyw9x3.aspx" rel="nofollow noreferrer">Locating the Assembly through Codebases or Probing</a>".</p>
<blockquote>
<p>Well, the loaded assembly doesn't have
an application configuration file.</p>
</blockquote>
<p>Well if you know the specific folders at runtime you can use <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx" rel="nofollow noreferrer">Assembly.LoadFrom</a>. </p>
| 4,205
|
<p>I just ran into an issue with Python's imaplib and Gmail's authentication mechanism:</p>
<pre><code>>>> import imaplib
>>> imap = imaplib.IMAP4_SSL('imap.gmail.com', 993)
>>> imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!')
Traceback (most recent call last):
...
imaplib.error: AUTHENTICATE command error: BAD ['TODO (not supported yet) 31if3458825wff.5']
</code></pre>
<p>If authentication is unsupported, how does one log in?</p>
|
<p>Instead of</p>
<pre><code>>>> imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!')
</code></pre>
<p>use</p>
<pre><code>>>> imap.login('bobdole@gmail.com', 'Bob Dole likes your style!')
</code></pre>
|
<p>I found the solution on <a href="http://codeclimber.blogspot.com/2008/06/using-ruby-for-imap-with-gmail.html" rel="nofollow noreferrer">this helpful blog post</a>. Although Gmail doesn't support AUTHENTICATE, it does support the LOGIN capability, like so:</p>
<pre><code>>>> imap.login('bobdole@gmail.com', 'Bob Dole likes your style!')
('OK', ['bobdole@gmail.com authenticated (Success)'])
</code></pre>
| 45,826
|
<p><a href="https://medifacd.relayhealth.com/Pharmacies/MediFacD_Pharmacies_PayerSheet_E1December2006.htm#Examples" rel="nofollow noreferrer" title="Medicare Eligibility EDI Example Responses">Medicare Eligibility EDI Example Responses</a> is what I'm trying to match.</p>
<p>I have a string that looks like this:</p>
<pre>LN:SMITHbbbbbbbbFN:SAMANTHAbbBD:19400515PD:1BN:123456PN:9876543210GP:ABCDEFGHIJKLMNOID:123456789012345bbbbbPC:123PH:8005551212CD:123456PB:123ED:20060101TD:2070101LC:NFI:12345678FE:20070101FT:20080101</pre>
<p>I need a set of matches that look like this:</p>
<pre>
Key | Value
-------------------
LN | SMITHbbbbbbbb
FN | SAMANTHAbb
BD | 19400515
... etc
</pre>
<p>I've been dealing with this all day, and I can't seem to get an acceptable matching scenario. I'm about to program it procedurally with a for loop and finding indexes of colons if I can't figure something out.</p>
<p>I've tried using <a href="http://yacsharpblog.blogspot.com/2008/09/regular-expressions-in-c-negative-look.html" rel="nofollow noreferrer" title="C# Negative Lookahead">negative lookahead</a> and I'm not getting anywhere. This is C#, and I'm using <a href="http://regexlib.com/RETester.aspx" rel="nofollow noreferrer" title=".Net Online Regular Expression Tester">this tester</a> (.Net) while I'm testing, along with <a href="http://www.weitz.de/regex-coach/" rel="nofollow noreferrer" title="The Regex Coach">The Regex Coach</a> (non .Net).</p>
<p>I've tried using this:</p>
<pre><code>([\w]{2})\:(?![\w]{2}\:)
</code></pre>
<p>But that only matches the keys and their colons, like "LN:", "FN:", etc.</p>
<p>If I use:</p>
<pre><code>([\w]{2})\:(.+?)([\w]{2})\:
</code></pre>
<p>It consumes the next matching two character key and colon as well, leading to me only matching every other key/value pair.</p>
<p>Is there a way for me to match these using RegEx in .Net correctly, or am I stuck with a more procedural solution? Keep in mind, I can't assume that the keys will always be upper case letters. They could possibly include numbers, but they will always be two characters and then a colon.</p>
<p>Thanks in advance for any help I can get.</p>
|
<p>I think what you want is positive lookahead, not negative, so that you find the key-colon combo ahead of the current position, but you don't consume it. This appears to work for your test example:</p>
<pre><code>([\w]{2})\:(.+?)(?=[\w]{2}\:|$)
</code></pre>
<p>Yielding:</p>
<pre>
LN: SMITHbbbbbbbb
FN: SAMANTHAbb
BD: 19400515
PD: 1
BN: 123456
PN: 9876543210
...
</pre>
<p>Note: I added the colons in my test output, they aren't captured by the regex.</p>
<p>EDIT: Thanks, Douglas, I've edited the regex to capture end-of-string so the last entry is captured, too.</p>
|
<p>This works in JavaScript (I always fire up the Error Console in Firefox to play around with regular expressions) but it should also work fine in .NET:</p>
<pre>([^:]{2}):((?:[^:](?!(?:[^:]:)))+)</pre>
<p>It uses negative lookahead:</p>
<pre>
( -> start capturing first token (the label)
[^:]{2} -> two non-colon characters
) -> end capturing first token
: -> skip the colon
( -> start capturing the second token (the value)
(?: -> don't capture this group as a token
[^:](?! -> a non-colon character, not followed by:
(?: -> don't capture this group
[^:]: -> a non-colon, followed by a colon
) -> end group
) -> end negative lookahead
)+ -> one or more of this group
) -> end capturing the second token
</pre>
<p>Test:</p>
<pre><code>"LN:SMITHbbbbbbbbFN:SAMANTHAbbBD:19400515"
.replace(
/([^:]{2}):((?:[^:](?!(?:[^:]:)))+)/g,
"[$1] = [$2]\n")
</code></pre>
<p>Yields:</p>
<pre>
[LN] = [SMITHbbbbbbbb]
[FN] = [SAMANTHAbb]
[BD] = [19400515]
</pre>
| 48,622
|
<p>Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.</p>
<p>For example:</p>
<pre><code>typedef std::bitset<16> WordSet;
</code></pre>
<p>Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler specific implementations are welcome, though I'm particularly interested in <code>g++</code>.</p>
|
<p>It's not possible in general to pick arbitrary template parameters.</p>
<p>However, the usual way you do it is this:</p>
<pre><code>template<int N>
struct foo {
static const int value = N;
};
</code></pre>
<p>and for types</p>
<pre><code>template<typename T>
struct foo {
typedef T type;
};
</code></pre>
<p>You can access it then as <code>foo<39>::value</code> or <code>foo<int>::type</code>.</p>
<p>If you have a particular type, you can use partial template specialization:</p>
<pre><code>template<typename>
struct steal_it;
template<std::size_t N>
struct steal_it< std::bitset<N> > {
static const std::size_t value = N;
};
</code></pre>
<p>The same principle is possible for type parameters too, indeed. Now you can pass any bitset to it, like <code>steal_it< std::bitset<16> >::value</code> (note to use size_t, not int!). Because we have no variadic many template paramters yet, we have to limit ourself to a particular parameter count, and repeat the steal_it template specializations for count from 1 up to N. Another difficulty is to scan types that have mixed parameters (types and non-types parameters). This is probably nontrivial to solve.</p>
<p>If you have not the type, but only an object of it, you can use a trick, to still get a value at compile time:</p>
<pre><code>template<typename T>
char (& getN(T const &) )[steal_it<T>::value];
int main() {
std::bitset<16> b;
sizeof getN(b); // assuming you don't know the type, you can use the object
}
</code></pre>
<p>The trick is to make the function template auto-deduce the type, and then return a reference to a character array. The function doesn't need to be defined, the only thing needed is its type.</p>
|
<p>In the case of <code>std::bitset</code>, you can just use the <code>size()</code> member function:</p>
<pre><code>size_t sz = oh_my_word.size(); // sz is now 16
</code></pre>
<p>In the general case, you can define a member function which returns the size in a similar manner:</p>
<pre><code>template <int N>
class Foo
{
public:
int size() const { return N; }
};
</code></pre>
| 38,628
|
<p>I would like to know how .NET teams out there are handling assembly reference paths when not everybody can immediately upgrade to a x64 operating system. The key issue right now is x64 versions of Windows will plant 32-bit installations into C:\Program Files (x86)\ instead of the regular C:\Program Files. This means many extra components and frameworks from 3rd parties end up in C:\Program Files (x86).</p>
<p>So when one downloads source projects created/modified in a x86 workstation onto a x64 workstation, there is some modification work required to get the reference paths correct. Quite typically, x64 users may save the modification and commit their "preferences" back into the version control repository, breaking the rhythm of the x86 users.</p>
<p>What are some good approaches to maintain harmony in a varied team?</p>
|
<p>Either install the assemblies in the GAC on each machine, or have a special LIB folder under your solution root that contains all your 3rd party assemblies. The LIB folder is what I've used for the last few years myself. I even put the assemblies in source control so other/new developers get them without having to think about it.</p>
|
<p>This is more of a follow-on question than an answer, but I thought this group might know.</p>
<p>What do we do if we have some devs working on 64 bit machines and some on 32 bit machines, but we need to reference unmanaged assemblies that need to be in x86 for half the team and x64 for the other half? Is there a solution besides manually updating the references every time someone on a 64 bit rig get latest?</p>
| 30,475
|
<p>I would like to store data persistently for my application, but I don't really need a full blown relational database. I really could get by with a basic "cache"-like <em>persistent</em> storage where the structure is just a (key, value) pair.</p>
<p>In lieu of a database what are my best, scalable options?</p>
|
<p>There's always <a href="http://www.sqlite.org/" rel="noreferrer">SQLite</a>, a database that's stored in a file. SQLite already has built-in concurrency, so you don't have to worry about things like file locking, and it's really fast for reads.</p>
<p>If, however, you are doing lots of database changes, it's best to do them all at once inside a <a href="http://www.sqlite.org/lang_transaction.html" rel="noreferrer">transaction</a>. This will only write the changes to the file once, as opposed to every time an change query is issued. This dramatically increases the speed of doing multiple changes.</p>
<p>When a change query is issued, whether it's inside a tranasction or not, the whole database is locked until that query finishes. This means that extremely large transactions could adversely affect the performance of other processes because they must wait for the transaction to finish before they can access the database. In practice, I haven't found this to be that noticeable, but it's always good practice to try to minimize the number of database modifying queries you issue.</p>
|
<p>If you want something really scalable, I wouldn't opt for a flat or XML file. As your data grows, it could kill your performance.</p>
<p>If you will have a lot of data <em>at some stage</em>, I would still opt for a database - I would take a look at something like <a href="http://www.sqlite.org/" rel="nofollow noreferrer">SQLIte</a> with a very simple schema to suit your needs.</p>
| 42,262
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.