instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>How do I create subdomain like <code>http://user.mywebsite.example</code>? Do I have to access <code>.htaccess</code> somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?</p>
<p>To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?</p>
|
<p>You're looking to create a custom <strong>A record</strong>.</p>
<p>I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:</p>
<pre><code>*.mywebsite.example IN A 127.0.0.1
</code></pre>
<p><em><code>127.0.0.1</code> would be the IP address of your webserver. The method of actually adding the record will depend on your host.</em></p>
<hr />
<p>Then you need to configure your web-server to serve all subdomains.</p>
<ul>
<li>Nginx: <code>server_name .mywebsite.example</code></li>
<li>Apache: <code>ServerAlias *.mywebsite.example</code></li>
</ul>
<p>Regarding .htaccess, you don't really need any rewrite rules. The <code>HTTP_HOST</code> header is available in PHP as well, so you can get it already, like</p>
<pre><code>$username = strtok($_SERVER['HTTP_HOST'], ".");
</code></pre>
<hr />
<p>If you don't have access to DNS/web-server config, doing it like <code>http://mywebsite.example/user</code> would be a lot easier to set up if it's an option.</p>
|
<h3>You can accomplish this via two steps.</h3>
<ol>
<li>Setup wildcard subdomain</li>
<li>Get the subdomain entered by user</li>
<li>Validate the subdomain</li>
</ol>
<hr />
<h3>1. Setup wildcard subdomain</h3>
<p>This might vary depending on your hosting provider. I use Namecheap.com, and the process was as simple as follows
<a href="https://i.stack.imgur.com/ZAGKC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZAGKC.png" alt="creating a sub domain in namecheap" /></a></p>
<ul>
<li>go to cPanel</li>
<li>go to sub domains</li>
<li>enter "*" as the value of subdomain</li>
</ul>
<p>Now every time you enter a random string before your domain name, it will direct to the wildcard sub domain. You can modify the contents of this wildcard subdomain.</p>
<h3>2. Get the subdomain entered by user</h3>
<p>You can now add a php file in the wildcard directory in file manager.</p>
<pre><code><?php
$link = $_SERVER['HTTP_HOST'];
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Wildcard Subdomain</title>
</head>
<body>
<h1>The visitor went to
<?php
echo "<br>";
print("link is: ".$link);
print("<br><br>");
echo "actual file: ".$actual_link;
?>
</h1>
</body>
</html>
</code></pre>
<h3>3. Validate the subdomain</h3>
<p>You might want to validate the sub domain to check if there is some user linked to it. This can be done with a check to a database.</p>
| 22,242
|
<p>I am creating a custom UserType in Hibernate for a project. It has been relatively straightforward until I came to the isMutable method. I am trying to figure out what this method means, contract-wise. </p>
<p>Does it mean the class I am creating the UserType for is immutable or does it mean the object that holds a reference to an instance of this class will never point to a different instance?</p>
<p>I found some examples in the <a href="http://www.hibernate.org/37.html" rel="noreferrer">Hibernate Community Wiki</a> where they returned true, because the object itself was mutable - <a href="http://www.hibernate.org/73.html" rel="noreferrer">http://www.hibernate.org/73.html</a>. </p>
<p>Other examples in the community wiki returned false without addressing why, even though they were also mutable.</p>
<p>I have checked the JavaDoc, but it's not very clear either.</p>
<p>From the JavaDoc for <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/usertype/UserType.html" rel="noreferrer">UserType</a>:</p>
<pre><code>public boolean isMutable()
Are objects of this type mutable?
Returns:
boolean
</code></pre>
<p>From JavaDoc for <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/type/Type.html" rel="noreferrer">Type</a>:</p>
<pre><code>public boolean isMutable()
Are objects of this type mutable. (With respect to the referencing
object ... entities and collections are considered immutable because
they manage their own internal state.)
Returns:
boolean
</code></pre>
|
<p>Hibernate will treat types marked as "mutable" as though they could change (i.e. require an UPDATE) <em>without</em> pointing to a new reference. If you assign a new reference to a Hibernate-loaded property Hibernate will recognize this even if the type is immutable - this happens all the time with, for instance, String fields.
But if, say, you have a StringBuilder field and you mark it as <em>immutable</em> Hibernate will <strong>not</strong> notice if you modify the StringBuilder.</p>
<p>See <a href="http://blog.xebia.com/2009/11/09/understanding-and-writing-hibernate-user-types/" rel="noreferrer">this blog post</a> for more details and a sample project.</p>
|
<p>The typical example here is the String class - it is Immutable, i.e. once the string is created you cannot change its contents or state, and if you want to then you're going to have to process it into a new copy. </p>
<p>isMutable returning true means you are saying this object can have its state changed by outside objects, returning false means you will have to copy this object to a new instance makign the changes to state along the way. Or as you said: "does it mean the object that holds a reference to an instance of this class will never point to a different instance".</p>
| 27,735
|
<p>Ok, here's one for the Java/JavaScript gurus:</p>
<p>In my app, one of the controllers passes a TreeMap to it's JSP. This map has car manufacturer's names as keys and Lists of Car objects as values. These Car objects are simple beans containing the car's name, id, year of production etc.
So, the map looks something like this (this is just an example, to clarify things a bit):</p>
<p>Key: Porsche<br/>
Value: List containing three Car objects(for example 911,Carrera,Boxter with their respectable years of production and ids)<br/>
Key: Fiat<br/>
Value: List containing two Car objects(for example, Punto and Uno)<br/>
etc...</p>
<p>Now, in my JSP i have two comboboxes. One should receive a list of car manufacturers(keys from the map - this part I know how to do), and the other one should <strong>dynamicaly change</strong> to display the names of the cars when the user selects a certain manufacturer from the first combobox. So, for example, user selects a "Porsche" in the first combobox, and the second immediately displays "911, Carrera, Boxter"...</p>
<p>After spending a couple of days trying to find out how to do this, I'm ready to admit defeat. I tried out a lot of different things but every time I hit a wall somewehere along the way. Can anybody suggest how I should approach this one?
Yes, I'm a JavaScript newbie, if anybody was wondering...
<br/></p>
<p>EDIT: I've retagged this as a code-challenge. Kudos to anybody who solves this one without using any JavaScript framework (like JQuery).</p>
|
<p>Well anyway, as i said, i finally managed to do it by myself, so here's my answer... </p>
<p>I receive the map from my controller like this (I'm using Spring, don't know how this works with other frameworks):</p>
<pre><code><c:set var="manufacturersAndModels" scope="page" value="${MANUFACTURERS_AND_MODELS_MAP}"/>
</code></pre>
<p>These are my combos:</p>
<pre><code><select id="manufacturersList" name="manufacturersList" onchange="populateModelsCombo(this.options[this.selectedIndex].index);" >
<c:forEach var="manufacturersItem" items="<%= manufacturers%>">
<option value='<c:out value="${manufacturersItem}" />'><c:out value="${manufacturersItem}" /></option>
</c:forEach>
</select>
</code></pre>
<p><br/></p>
<pre><code>select id="modelsList" name="modelsList"
<c:forEach var="model" items="<%= models %>" >
<option value='<c:out value="${model}" />'><c:out value="${model}" /></option>
</c:forEach>
</select>
</code></pre>
<p>I imported the following classes (some names have, of course, been changed):</p>
<pre><code><%@ page import="org.mycompany.Car,java.util.Map,java.util.TreeMap,java.util.List,java.util.ArrayList,java.util.Set,java.util.Iterator;" %>
</code></pre>
<p>And here's the code that does all the hard work:</p>
<pre><code><script type="text/javascript">
<%
Map mansAndModels = new TreeMap();
mansAndModels = (TreeMap) pageContext.getAttribute("manufacturersAndModels");
Set manufacturers = mansAndModels.keySet(); //We'll use this one to populate the first combo
Object[] manufacturersArray = manufacturers.toArray();
List cars;
List models = new ArrayList(); //We'll populate the second combo the first time the page is displayed with this list
//initial second combo population
cars = (List) mansAndModels.get(manufacturersArray[0]);
for(Iterator iter = cars.iterator(); iter.hasNext();) {
Car car = (Car) iter.next();
models.add(car.getModel());
}
%>
function populateModelsCombo(key) {
var modelsArray = new Array();
//Here goes the tricky part, we populate a two-dimensional javascript array with values from the map
<%
for(int i = 0; i < manufacturersArray.length; i++) {
cars = (List) mansAndModels.get(manufacturersArray[i]);
Iterator carsIterator = cars.iterator();
%>
singleManufacturerModelsArray = new Array();
<%
for(int j = 0; carsIterator.hasNext(); j++) {
Car car = (Car) carsIterator.next();
%>
singleManufacturerModelsArray[<%= j%>] = "<%= car.getModel()%>";
<%
}
%>
modelsArray[<%= i%>] = singleManufacturerModelsArray;
<%
}
%>
var modelsList = document.getElementById("modelsList");
//Empty the second combo
while(modelsList.hasChildNodes()) {
modelsList.removeChild(modelsList.childNodes[0]);
}
//Populate the second combo with new values
for (i = 0; i < modelsArray[key].length; i++) {
modelsList.options[i] = new Option(modelsArray[key][i], modelsArray[key][i]);
}
}
</code></pre>
<p></p>
|
<p>How about something like this, using prototype? First, your select box of categories:</p>
<pre><code><SELECT onchange="changeCategory(this.options[this.selectedIndex].value); return false;">
<OPTION value="#categoryID#">#category#</OPTION>
...
</code></pre>
<p>Then, you output N different select boxes, one for each of the sub-categories:</p>
<pre><code><SELECT name="myFormVar" class="categorySelect">
...
</code></pre>
<p>Your changeCategory javascript function disables all selects with class categorySelect, and then enables just the one for your current categoryID. </p>
<pre><code>// Hide all category select boxes except the new one
function changeCategory(categoryID) {
$$("select.categorySelect").each(function (select) {
select.hide();
select.disable();
});
$(categoryID).show();
$(categoryID).enable();
}
</code></pre>
<p>When you hide/disable like this in prototype, it not only hides it on the page, but it will keep that FORM variable from posting. So even though you have N selects with the same FORM variable name (myFormVar), only the active one posts.</p>
| 18,982
|
<p>I need to get the image dimensions of a JPEG in C++. I'm looking for either a fairly simple way to do it or a smallish library that provides that functionality. I'm working in C++ on OpenVMS, so any external libraries may have to be adapted to compile on our systems - so please don't post me links to big, closed source libraries!</p>
<p>Has anyone come across anything that might do the trick, or understand the JPEG file format (I think I probably mean the JFIF file format here) to tell me how I might go about rolling my own solution?</p>
|
<p>You have this <a href="http://carnage-melon.tom7.org/stuff/jpegsize.html" rel="nofollow noreferrer">C function</a> which may extract the relevant data for you.</p>
<blockquote>
<p>This is a C routine but should compile fine with C++.<br>
Pass it a normal FILE pointer (from fopen) to the beginning of a jpeg file and two int pointers to be set with the image height and width. </p>
</blockquote>
<p>Or you may find in the <a href="http://www.boost.org/doc/libs/1_35_0/boost/gil/extension/io/jpeg_io.hpp" rel="nofollow noreferrer">Boost library</a> a jpeg class which has the right function (From <a href="http://www.adobe.com/technology/graphics/generic_image_library.html" rel="nofollow noreferrer">Adobe</a> <a href="http://opensource.adobe.com/wiki/display/gil/Generic+Image+Library" rel="nofollow noreferrer">Generic Image Library</a>).</p>
<p><a href="http://stlab.adobe.com/gil/html/group___j_p_e_g___i_o.html#ga4" rel="nofollow noreferrer">jpeg_read_dimensions</a> </p>
<pre><code>boost::gil::jpeg_read_dimensions (const char *filename)
</code></pre>
<blockquote>
<p>Returns the width and height of the JPEG file at the specified location. Throws std::ios_base::failure if the location does not correspond to a valid JPEG file. </p>
</blockquote>
|
<p>You may want to try <a href="https://gdal.org/" rel="nofollow noreferrer">GDAL</a> library which serves as an abstraction layer for large number of raster data formats, mostly used in geospatial applications for GIS/RS.</p>
<p>GDAL provides number of APIs, for C, C++ and scripting languages. Of course, it supports <a href="https://gdal.org/frmt_jpeg.html" rel="nofollow noreferrer">JPEG</a> images and its variants like <a href="https://web.archive.org/web/20210302193335/https://gdal.org/frmt_jpeg2000.html" rel="nofollow noreferrer">JPEG2000</a> and more.</p>
<p>Here is a very simple example how to open JPEG image and query its dimensions:</p>
<pre><code>#include <gdal_priv.h>
GDALAllRegister(); // call ones in your application
GDALDataset* ds = (GDALDataset*)GDALOpen("my.jpeg", GA_ReadOnly);
int width = ds->GetRasterXSize();
int height = ds->GetRasterYSize(),
int nbands = ds->GetRasterCount();
</code></pre>
<p>Check <a href="https://gdal.org/tutorials/raster_api_tut.html" rel="nofollow noreferrer">GDAL API tutorial</a> for more complete example.</p>
| 40,960
|
<p>How would I go about binding the following object, Car, to a gridview?</p>
<pre>
public class Car
{
long Id {get; set;}
Manufacturer Maker {get; set;}
}
public class Manufacturer
{
long Id {get; set;}
String Name {get; set;}
}
</pre>
<p>The primitive types get bound easy but I have found no way of displaying anything for Maker. I would like for it to display the Manufacturer.Name. Is it even possible? </p>
<p>What would be a way to do it? Would I have to store ManufacturerId in Car as well and then setup an lookupEditRepository with list of Manufacturers?</p>
|
<p>Allright guys... This question was posted waaay back but I just found a fairly nice & simple way to do this by using reflection in the cell_formatting event to go retrieve the nested properties.</p>
<p>Goes like this:</p>
<pre><code> private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView grid = (DataGridView)sender;
DataGridViewRow row = grid.Rows[e.RowIndex];
DataGridViewColumn col = grid.Columns[e.ColumnIndex];
if (row.DataBoundItem != null && col.DataPropertyName.Contains("."))
{
string[] props = col.DataPropertyName.Split('.');
PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]);
object val = propInfo.GetValue(row.DataBoundItem, null);
for (int i = 1; i < props.Length; i++)
{
propInfo = val.GetType().GetProperty(props[i]);
val = propInfo.GetValue(val, null);
}
e.Value = val;
}
}
</code></pre>
<p>And that's it! You can now use the familiar syntax "ParentProp.ChildProp.GrandChildProp" in the DataPropertyName for your column.</p>
|
<p>I would assume you could do the following:</p>
<pre><code>public class Car
{
public long Id {get; set;}
public Manufacturer Maker {private get; set;}
public string ManufacturerName
{
get { return Maker != null ? Maker.Name : ""; }
}
}
public class Manufacturer
{
long Id {get; set;}
String Name {get; set;}
}
</code></pre>
| 14,752
|
<p>I don't expect a straightforward silver bullet answer to this, but what are the best practices for ensuring good performance for SharePoint 2007 sites?</p>
<p>We've a few sites for our intranet, and it generally is thought to run slow. There's plenty of memory and processor power in the servers, but the pages just don't 'snap' like you'd expect from a web site running on powerful servers.</p>
<p>We've done what we can to tweak setup, but is there anything we could be missing?</p>
|
<p>Andrew Connell's latest book (Professional SharePoint 2007 Web Content Management Development) has an entire chapter dedicated to imporving performance of SharePoint sites.</p>
<p>Key topics it covers are Caching, Limiting page load (particularly how to remove CORE.js if it's not needed), working with Disposable objects and how to work with SharePoint querying.</p>
<p>2 really good tricks I've got are to use the CSS Freindly Control Adapters to generate smaller HTML for the common components (menus, etc) and setting up a server "wake up", so when IIS sleeps the app-pool due to inactivity you can reawaken it before someone hits your site.</p>
|
<p>Just a few ideas...</p>
<p>Is displaying your pages as slow when doing it from the Server or from a Client? If slower from client, do check your network.</p>
<p>Are your pages very "heavy"? (means, many elements, web parts and so on?) Than maybe it's normal.</p>
<p>Have you noticed they load slowlier since you've add one specific web part? Maybe there's some issues with that specific web part (for example, it's accessing to a document library that has many -thousands of- documents). If that's the case, try to deactivate that specific web part and see if the performance works better.</p>
| 13,745
|
<p>One of the stated goals of the PureMVC framework is to avoid platform dependencies in order to be portable. Considering that because of language and API differences application code will always be heavily dependent on the platform, and that avoiding platform dependencies makes the framework reinvent the wheel and/or only provide a least-common-denominator feature set, in what way does the portability of the framework benefit me as an application developer?</p>
|
<p>I've worked with PureMVC. They're trying to implement their stuff in quite a lot of languages. You may be right about the least common denominator, but overall, it's not a bad framework, and I've seen a really nice AS3 app in PureMVC.</p>
<p>I don't think they're talking about portability in terms of porting actual code. The idea there is more that you're using a generalized MVC architecture, which you could apply to other projects and other languages.</p>
<p>They're trying to say that if you become familiar with the PureMVC pattern, you could potentially come into a new PureMVC codebase, even if it's another language, and you would already know the lay of the land.</p>
<p>You might also say that developers who develop good PureMVC skills are likely to develop good habits which will translate as they go from language to language. But then again, maybe not.. for the reasons you mentioned.</p>
|
<p>Are there examples of people using PureMVC to build and port applications across multiple platforms?</p>
<p>My company is building a Flex application that we may need to port to other platforms:</p>
<ul>
<li>Silverlight (likely)</li>
<li>Mobile (maybe)</li>
<li>Desktop (maybe -- not just AIR!)</li>
<li>TV sets (maybe eventually)</li>
</ul>
<p>I am considering PureMVC as a framework if it can ease porting and maintenance. I am curious to know if other people have ported a PureMVC app to a different platform and what their experience was with porting and then having development proceed in parallel for the app on multiple platforms.</p>
<p>Cheers,</p>
<p>Karthik</p>
| 17,317
|
<p>I have some content that i have to render as a excel file in browser. I was able to render a grid content to excel with the below code.</p>
<pre><code> Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
htmlWrite.Write(stringWrite);
Response.Write(stringWrite.ToString());
Response.End();
</code></pre>
<p>Now i have to do a similar thing for a image. That is, i want a code that can render a image to excel. </p>
<p>I mean when the user opens the excel he should be able to see the image in it. </p>
<p>Is it possible to convert the image to base64sting format and put it into the excel?</p>
<p>Please let me know if you have any idea similar to this. </p>
<p>Thanks
Vinod T.</p>
|
<p>I've been using the same kind of hacks to get grid data (html tagged) into excel.</p>
<p>If it is HTML data you are writing there, just add <IMG SRC="MYFILENAME.JPG> into the HTML text where you want the images.</p>
<p>What will happen, is that Excel will ask your server (asp.net app) for that file.</p>
<p>You might have to add a full path to the image
<IMG SRC="http://myserver/subpath/MYFILENAME.JPG></p>
<p>Using a packet sniffer, I have verified that Excel in deed will ask for the IMG file, so just make sure you have placed the image ready for download. (either as an asp.net stream) or physically.</p>
<p>My test HTML.<br>
<html><br>
<table><br>
<tr><td>test</td><td>test</td<td>test</td></tr><br>
<tr><td>test</td><td>test</td><td>test</td></tr><br>
<tr><td>test</td><td>test</td><td><img
src="http://myserver/LALLAALLAA.jpg"></td></tr>
<br>
</table><br>
</html></p>
<p>If ONLY Image, its the same as over only with no table tags at all. Just the HTML and IMG tag.</p>
|
<p>Oh. Another more complex way would be to create a .MHT file (webarchive) file. That contain both the HTML and images embedded in the same file.
That way you only have one stream out. But I dont know if Excel will recognize the MHT content and show it.</p>
| 36,997
|
<p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
|
<pre><code>#!/usr/bin/python
import random
import string
digits = "".join( [random.choice(string.digits) for i in xrange(8)] )
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
print digits + chars
</code></pre>
<p>EDIT: liked the idea of using random.choice better than randint() so I've updated the code to reflect that. </p>
<p>Note: this assumes lowercase and uppercase characters are desired. If lowercase only then change the second list comprehension to read:</p>
<pre><code>chars = "".join( [random.choice(string.letters[:26]) for i in xrange(15)] )
</code></pre>
<p>Obviously for uppercase only you can just flip that around so the slice is [26:] instead of the other way around.</p>
|
<p>Here's a simpler version:</p>
<pre><code>import random
import string
digits = "".join( [random.choice(string.digits+string.letters) for i in xrange(10)] )
print digits
</code></pre>
| 47,978
|
<p>Is there a case insensitive version of the <a href="http://docs.jquery.com/Selectors/contains" rel="noreferrer">:contains</a> jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?</p>
|
<p>What I ended up doing for jQuery 1.2 is :</p>
<pre><code>jQuery.extend(
jQuery.expr[':'], {
Contains : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0"
});
</code></pre>
<p>This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged.</p>
<p>Edit: For jQuery 1.3 (thanks @user95227) and later you need</p>
<pre><code>jQuery.expr[':'].Contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
</code></pre>
<p>Edit:
Apparently accessing the DOM directly by using</p>
<pre><code>(a.textContent || a.innerText || "")
</code></pre>
<p>instead of </p>
<pre><code>jQuery(a).text()
</code></pre>
<p>In the previous expression speeds it up considerably so try at your own risk if speed is an issue. (see <a href="https://stackoverflow.com/users/171662/john">@John</a> 's <a href="https://stackoverflow.com/questions/1407434/is-there-any-way-to-speed-up-this-solution-for-a-case-insensitive-jquery-contai">question</a>)</p>
<p>Latest edit: For jQuery 1.8 it should be:</p>
<pre><code>jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
return function( elem ) {
return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
</code></pre>
|
<p>I had a similar problem with the following not working...</p>
<pre><code>// This doesn't catch flac or Flac
$('div.story span.Quality:not(:contains("FLAC"))').css("background-color", 'yellow');
</code></pre>
<p>This works and without the need for an extension</p>
<pre><code>$('div.story span.Quality:not([data*="flac"])').css("background-color", 'yellow');
</code></pre>
<p>This works too, but probably falls into the "manually looping" category....</p>
<pre><code>$('div.story span.Quality').contents().filter(function()
{
return !/flac/i.test(this.nodeValue);
}).parent().css("background-color", 'yellow');
</code></pre>
| 22,715
|
<p>What is the functional programming approach to convert an <code>IEnumerable<string></code> to a delimited string? I know I can use a loop, but I'm trying to wrap my head around functional programming. </p>
<p>Here's my example: </p>
<pre><code>var selectedValues =
from ListItem item in checkboxList.Items
where item.Selected
select item.Value;
var delimitedString = ??
</code></pre>
<p>.. or could I do this in just the first var assignment (append each result to the previous)?</p>
|
<pre><code>string.Join(", ", string[] enumerable)
</code></pre>
|
<p>This is 3.5 compatible:</p>
<pre><code>var selectedValues = String.Join(",", (from ListItem item in checkboxList.Items where item.Selected select item.Value).ToArray());
</code></pre>
| 20,184
|
<p>Yesterday @headius / Charles Nutter came up with a very interesting idea on twitter:</p>
<blockquote>
<p>@danny_l Gafter made the same mistake; I don't mean a forked Java any more than Groovy is a fork. I want a "mostly Java" with closures. </p>
</blockquote>
<p>or the reply by @danny_l / Danny Lagrouw:</p>
<blockquote>
<p>@headius or could the BGGA prototype be "bolted on" any future version of Java? That might be useful </p>
</blockquote>
<p>That really is what I would like to see as well. Can't we have some sort of bytecode preprocessor to make the BGGA prototype work on any modern Java version? I mean scala, Groovy and JRuby have closures and produce valid bytecode!</p>
<p>I would even like to help and put effort in it. Although I don't really know where to start.</p>
<p>(the above is an excerpt of the <a href="http://maas-frensch.com/peter/2008/10/11/i-want-closures-bolted-on-to-java/" rel="nofollow noreferrer">blogpost</a> I wrote about this topic)</p>
<p>What do others think of this idea?</p>
|
<p>The word 'preprocessor' takes me back to C++ and it scares me. </p>
<p>There is a weird dichotomy: I celebrate the diverse garden of languages on the JVM, but I think that "Mama Bear" (aka Java) should not become fragmented like this. We need a solid foundation.</p>
<p>That said, I am in favour of BGGA closures. I also think a language should provide its full capabilities. If a team has people who can't handle closures (or generics, or threading (!!)), then that team should police itself through code reviews and static analysis. </p>
<p>Maybe one idea would be to have a compile-time switch to 'disallow' advanced features like this but even that seems a bit harsh.</p>
<p>I think the 'bolt-on' idea is really trying to address the fractured leadership in the Java space. That problem strikes as being more political and diplomatic than technical.</p>
|
<p>The problem with making these things a bolt on is that you create a fragmented language. </p>
<p>The java language is the smallest part of what makes java, java. The libraries and the culture make up the larger part. Making closures and generics a bolt on means that either they cannot be used in the core libraries or that the core libraries would require the bolt on to be present in the SDK being used. This would at best create fragmentation within the libraries (as some developers work to the core and some require the bolt-on) and at worst would mean that we will start having 'distributions' of java in the manor of java each containing a different set of jars and 'bolt-ons'.</p>
<p>I would say this is the start of a slippery slop I would rather stay off of.</p>
| 23,555
|
<p>When I subscribe for a report, I may chose to have a subject like: <code>@ReportName was executed at: @ExecutionTime</code></p>
<p>I would like a name like this: <code>Your "@ReportName" report covering Sep 10 2008 - Sep 16 2008</code></p>
<p><code>Sep 10 2008 - Sep 16 2008</code> are values of the two report parameters: <code>@DateFrom</code> and <code>@DateTo</code>, respectively.</p>
<p>Can I specify something like <code>@ReportParameters!DateFrom</code> as my subject?</p>
|
<p>Check out <a href="http://www.sqlservercentral.com/articles/Development/datadrivensubscriptions/2432/" rel="nofollow noreferrer">this article</a>. The author shows how to execute a data driven subscription from code and provides a stored procedure for doing so. The stored procedure allows you to specify the email body so if you know the report parameters before running the report you could populate them before calling the procedure. I'm not sure if his procedure covers email subjects, but perhaps you could take what he has done and modify it.</p>
<p>Also just found <a href="https://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3656006&SiteID=1" rel="nofollow noreferrer">this MSDN forum post</a> with a response from MSFT that this a data driven subscription is the way to accomplish this.</p>
|
<p>I don't believe anything other than those 2 parameters are available to report subscription emails (at least in SSRS 2005). </p>
<p>You may be able to do something via a data-driven subscription, but the values you want to use need to be in the data source used for the subscription data - SSRS is still not able to collect data in the report itself.</p>
| 10,864
|
<p>Requirement is to pass module name and function name from the command-line argument.
I need to get the command-line argument in the program and I need to call that function from that module</p>
<p>For example, calling a try.pl program with 2 arguments: MODULE1(Module name) Display(Function name)</p>
<pre><code> perl try.pl MODULE1 Display
</code></pre>
<p>I want to some thing like this, but its not working, please guide me: </p>
<pre><code>use $ARGV[0];
& $ARGV[0]::$ARGV[1]();
</code></pre>
|
<p>There's many ways to do this. One of them is:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
my ( $package, $function ) = @ARGV;
eval "use $package; 1" or die $@;
$package->$function();
</code></pre>
<p>Note the the first argument of the function will be $package.</p>
|
<p>I'd use <a href="http://search.cpan.org/~mschwern/UNIVERSAL-require-0.10/lib/UNIVERSAL/require.pm" rel="nofollow noreferrer">UNIVERSAL::require</a>. It allows you to require or use a module from a variable. So your code would change to something like this: </p>
<pre><code>use UNIVERSAL::require;
$ARGV[0]->use or die $UNIVERSAL::require::ERROR;
$ARGV[0]::$ARGV[1]();
</code></pre>
<p>Disclaimer: I did not test that code and I agree Robert P's comment about there probably being a better solution than passing these as command line arguments. </p>
| 25,653
|
<p>At the moment I am using Visual Source Safe (yeah yeah!) to store my Technical Specification documentation.</p>
<p>The actual docs are written in MS word.</p>
<p>If find that having the spec written in word format to be a big burden, for specs to be truly used there shouldn't be any barrier to usage and more importantly <b>access</b>.</p>
<p>If I can't quickly scan a document, hyperlink to other dependant documents or sections, what use is all this anyway?</p>
<p>So with that as a background:</p>
<p><b>what software exists to create truly accessable documentation? i.e. hyperlinks to other pages/sections etc? Or even queryable so I can view all documents that are dependant on module 4.5.3</b></p>
<p>Is it basically just a Wiki? Anything else?</p>
|
<p>Wikis are great for creating and maintaining specs. However, it is difficult to generate a big ol' paper document that makes a satisfying "thud" when you drop it on peoples' desks.</p>
<p>I've gotten by with Word. Just learn to take advantage of all the automation it has for cross-referencing, indexes, tables, pagination, etc.</p>
<p>I think of specs as having two audiences: decision-makers and developers. The Word documents are for the decision makers. The developers will come up with something useful later when it is time to implement the specs.</p>
|
<p>I believe Word supports the idea of sub-documents (links to other documents), however I'm not sure how well it works without VSS, much less with VSS. But it's something to look into.</p>
<p>A wiki is, however, pretty much what you are looking for.</p>
| 29,832
|
<p>It may sound stupid, but sometimes I run into version conflicts between two versions of subversion. I mount a directory on a development server with sshfs and then edit the code with my local Vim. For subversion stuff like updating, committing etc. I ssh on the server and do it there. However, sometimes I mix up my shells and accidently do an update or commit in my local shell in the mounted directory. Subversion exits with an error, which is fine. However, when I try to do the same thing on the development server in my ssh session, subversion says that the working directory/subversion has a wrong version. The subversion version on the server is older than the version on my notebook, so I guess my (newer) version somehow upgrades the working directories so they are incompatible with the old version on the development server. Sometimes deleting the .svn/lock files helps, but only if I do it right after I executed the subversion command on my notebook. When I execute the command on the development server afterwards, the lock files disappear and I don't see a way to rescue the checkout. This wouldn't be so bad if the repository wasn't that big. Especially when I made lots of changes and can't commit them.</p>
<p>The only solution I see at the moment is to copy the files I changed somewhere, remove the checkout, do a complete new checkout and copy the files back.</p>
<p>Is there a better solution to rescue a broken checkout and/or my changes?</p>
<p><strong>UPDATE</strong>
The FAQ Mikael Sundberg linked contained the answer. I write it down here, because he doesn't explictictly mention it. There's a script that can downgrade upgraded repositories, when it's safe:</p>
<p><a href="http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/change-svn-wc-format.py" rel="nofollow noreferrer">http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/change-svn-wc-format.py</a></p>
|
<p>Maybe this FAQ-entry could be helpful:
<a href="http://subversion.tigris.org/faq.html#working-copy-format-change" rel="nofollow noreferrer">http://subversion.tigris.org/faq.html#working-copy-format-change</a></p>
|
<p>I am not sure if I understand correctly your problem, but here are some tips:</p>
<p>First one tip -- did you try SVN <em>Clean</em> command?</p>
<p>The next one is probably useless for you:), but many people used to use CVS don't realize that SVN has feature like that, so I write it down.</p>
<p>If you use Windows and <a href="http://tortoisesvn.tigris.org/" rel="nofollow noreferrer">Tortoise SVN client</a> you can choose <em>Show Log</em> command from context menu (right mouse button). When the list of check-ins appear choose the last good one one and choose from context menu command <em>revert to this revision</em>.</p>
<p>In other case (not Windows nor Tortoise SVN), investigate <a href="http://svnbook.red-bean.com/en/1.1/index.html" rel="nofollow noreferrer">documentation</a> for command-line version of commands described above.</p>
<p>Next tip could help you avoid mixing your shells.</p>
<p>You've written that you use SSH shell -- to avoid problems with mixing shell sessions I always use different background color for each server (and account), which I log-in (i.e. white on black for development, yellow on navy on testing server and yellow on green on production server).</p>
<p>This saves me many times :).</p>
| 16,417
|
<p>How to find fifth highest salary in a single query in SQL Server</p>
|
<p>In SQL Server 2005 & 2008, create a ranked subselect query, then add a where clause where the rank = 5.</p>
<pre><code>select
*
from
(
Select
SalesOrderID, CustomerID, Row_Number() Over (Order By SalesOrderID) as RunningCount
From
Sales.SalesOrderHeader
Where
SalesOrderID > 10000
Order By
SalesOrderID
) ranked
where
RunningCount = 5
</code></pre>
|
<p>You can try some thing like :</p>
<pre><code>select salary
from Employees a
where 5=(select count(distinct salary)
from Employees b
where a.salary > b.salary)
order by salary desc
</code></pre>
| 46,755
|
<p>I'm looking into tightening up our ad code by moving it to an external jQuery script, but I obviously still need some HTML to target the ad to. So I was wondering if I can target a noscript element (or within a noscript element) since I'm going to have to leave that on the page anyway, or if I need to have some other element for the JavaScript to target?</p>
<pre><code><noscript>
<div class="ad"><a href="foo"><img src="bar" alt="ad" /></a></div>
</noscript>
</code></pre>
<p>My intention would be to change or strip the noscript element.</p>
|
<p><code><noscript></code> content is not only not displayed when JS is active, it apparently is also not in the DOM. I tried accessing content inside a <code><noscript></code> area (hoping you could <code>clone()</code> it with jQuery and insert it somewhere else) but got back nothing.</p>
|
<p>You could always use the JS to hide that ad using CSS, if nothing else.</p>
| 34,288
|
<p>I'm using a the TreeView control and it scrolls automatically to left-align TreeViewItem when one of them is clicked. I've gone looking at my Styles and ControlTemplates, but I haven't found anything. Is there a default ControlTemplate that causes this? I want to disable it.</p>
|
<p>The items scroll because the ScrollViewer calls BringIntoView() on them. So one way to avoid scrolling is to suppress the handling of the RequestBringIntoView event. You can try that out quickly by subclassing TreeView and instantiating this control instead:</p>
<pre><code>public class NoScrollTreeView : TreeView
{
public class NoScrollTreeViewItem : TreeViewItem
{
public NoScrollTreeViewItem() : base()
{
this.RequestBringIntoView += delegate (object sender, RequestBringIntoViewEventArgs e) {
e.Handled = true;
};
}
protected override DependencyObject GetContainerForItemOverride()
{
return new NoScrollTreeViewItem();
}
}
protected override DependencyObject GetContainerForItemOverride()
{
return new NoScrollTreeViewItem();
}
}
</code></pre>
|
<p>It looks like I found a good clue on <a href="http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9abff78f-481d-4db1-a545-c461f7d19200/" rel="nofollow noreferrer">MSDN</a>:</p>
<blockquote>
<p>Sounds like this is an interaction
with the scrollviewer and the focus
system.</p>
<p>When an element is focused within a
ScrollViewer (which is part of the
TreeView template), the ScrollViewer
is instructed to make the element
visible. It automatically responds by
scrolling to the requested element.</p>
<p>The methods inside of ScrollViewer
that handle these focus requests are
all private and / or internal so you
really can't get to them. I don't
think there's too much you can do in
this case; it's just how focus works.</p>
</blockquote>
<p>So, is that it? Surely there's a way to modify the TreeView template so that the ScrollViewer won't have this behavior...</p>
| 30,384
|
<p>How do I convert the value of a PHP variable to string?</p>
<p>I was looking for something better than concatenating with an empty string:</p>
<pre><code>$myText = $myVar . '';
</code></pre>
<p>Like the <code>ToString()</code> method in Java or .NET.</p>
|
<p>You can use the <a href="http://us3.php.net/manual/en/language.types.type-juggling.php" rel="noreferrer">casting operators</a>:</p>
<pre><code>$myText = (string)$myVar;
</code></pre>
<p>There are more details for string casting and conversion in the <a href="http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting" rel="noreferrer">Strings section</a> of the PHP manual, including special handling for booleans and nulls.</p>
|
<p>I use <a href="https://github.com/lingtalfi/VariableToString" rel="nofollow noreferrer">variableToString</a>. It handles every PHP type and is flexible (you can extend it if you want).</p>
| 4,775
|
<p>The web applications I develop often require co-dependent configuration settings and there are also settings that have to change as we move between each of our environments.</p>
<p>All our settings are currently simple key-value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment.</p>
<p>What's the best way to create custom config sections and are there any special considerations to make when retrieving the values?</p>
|
<p><strong>Using attributes, child config sections and constraints</strong></p>
<p>There is also the possibility to use attributes which automatically takes care of the plumbing, as well as providing the ability to easily add constraints.</p>
<p>I here present an example from code I use myself in one of my sites. With a constraint I dictate the maximum amount of disk space any one user is allowed to use.</p>
<p>MailCenterConfiguration.cs:</p>
<pre><code>namespace Ani {
public sealed class MailCenterConfiguration : ConfigurationSection
{
[ConfigurationProperty("userDiskSpace", IsRequired = true)]
[IntegerValidator(MinValue = 0, MaxValue = 1000000)]
public int UserDiskSpace
{
get { return (int)base["userDiskSpace"]; }
set { base["userDiskSpace"] = value; }
}
}
}
</code></pre>
<p>This is set up in web.config like so</p>
<pre><code><configSections>
<!-- Mailcenter configuration file -->
<section name="mailCenter" type="Ani.MailCenterConfiguration" requirePermission="false"/>
</configSections>
...
<mailCenter userDiskSpace="25000">
<mail
host="my.hostname.com"
port="366" />
</mailCenter>
</code></pre>
<p><strong>Child elements</strong></p>
<p>The child xml element <em>mail</em> is created in the same .cs file as the one above. Here I've added constraints on the port. If the port is assigned a value not in this range the runtime will complain when the config is loaded.</p>
<p>MailCenterConfiguration.cs:</p>
<pre><code>public sealed class MailCenterConfiguration : ConfigurationSection
{
[ConfigurationProperty("mail", IsRequired=true)]
public MailElement Mail
{
get { return (MailElement)base["mail"]; }
set { base["mail"] = value; }
}
public class MailElement : ConfigurationElement
{
[ConfigurationProperty("host", IsRequired = true)]
public string Host
{
get { return (string)base["host"]; }
set { base["host"] = value; }
}
[ConfigurationProperty("port", IsRequired = true)]
[IntegerValidator(MinValue = 0, MaxValue = 65535)]
public int Port
{
get { return (int)base["port"]; }
set { base["port"] = value; }
}
</code></pre>
<p><strong>Use</strong></p>
<p>To then use it practically in code, all you have to do is instantiate the MailCenterConfigurationObject, this will <strong>automatically</strong> read the relevant sections from web.config.</p>
<p>MailCenterConfiguration.cs</p>
<pre><code>private static MailCenterConfiguration instance = null;
public static MailCenterConfiguration Instance
{
get
{
if (instance == null)
{
instance = (MailCenterConfiguration)WebConfigurationManager.GetSection("mailCenter");
}
return instance;
}
}
</code></pre>
<p>AnotherFile.cs</p>
<pre><code>public void SendMail()
{
MailCenterConfiguration conf = MailCenterConfiguration.Instance;
SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port);
}
</code></pre>
<p><strong>Check for validity</strong></p>
<p>I previously mentioned that the runtime will complain when the configuration is loaded and some data does not comply to the rules you have set up (e.g. in MailCenterConfiguration.cs). I tend to want to know these things as soon as possible when my site fires up. One way to solve this is load the configuration in _Global.asax.cx.Application_Start_ , if the configuration is invalid you will be notified of this with the means of an exception. Your site won't start and instead you will be presented detailed exception information in the <a href="http://www.codinghorror.com/blog/images/yellow-screen-of-death-large.png" rel="noreferrer">Yellow screen of death</a>.</p>
<p>Global.asax.cs</p>
<pre><code>protected void Application_ Start(object sender, EventArgs e)
{
MailCenterConfiguration.Instance;
}
</code></pre>
|
<p>You can accomplish this with Section Handlers. There is a basic overview of how to write one at <a href="http://www.codeproject.com/KB/aspnet/ConfigSections.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/aspnet/ConfigSections.aspx</a> however it refers to app.config which would be pretty much the same as writing one for use in web.config. This will allow you to essentially have your own XML tree in the config file and do some more advanced configuration.</p>
| 2,435
|
<p>Ender 3 Pro, PLA, temps 200 °C and 60 °C.</p>
<p>I want to not heat the nozzle until after Auto Bed Leveling (CR Touch) is complete. I can do that in the start G-code, but by then, Cura has already heated the nozzle to the temp specified under material and filament starts oozing out during bed leveling. I'd rather set a variable to that value and call it with <code>M104</code> when I'm ready.</p>
<p>This is the start of Cura's g-code:</p>
<pre><code>;FLAVOR:Marlin
;TIME:2888
;Filament used: 1.96332m
;Layer height: 0.2
;MINX:93.266
;MINY:10.195
;MINZ:0.2
;MAXX:126.734
;MAXY:210.658
;MAXZ:4.2
;Generated with Cura_SteamEngine 4.13.1
M140 S60
M105
M190 S60
M104 S200
M105
M109 S200
M82 ;absolute extrusion mode
; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
G29 ; Auto Bed Level (CR Touch)
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
...
</code></pre>
<p>The lines right after "Generated with Cura_SteamEngine" are the ones I'd like to change but I can't find them in the Cura app. I know that 60 °C and 200 °C are the temps defined for bed and nozzle. Cura inserts them as constants for the <code>M140</code> and <code>M104</code> commands. I'd like Cura to set variables to those values (like <code>{bed_temp} = 60</code>) so I can refer to that variable when I insert the <code>M140</code> command in my Custom Start G-code. Can that be done?</p>
<p>A related question was asked a few years ago and part of the start code example then was:</p>
<pre><code>; Ender 3 Custom Start G-code
M104 S{material_print_temperature_layer_0} ; Set Extruder temperature
M140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature
G28 ; Home all axes
G29 ; BLTOUCH Mesh Generation
M190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature
M109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature
</code></pre>
<p>The variable <code>{material_bed_temperature_layer_0}</code> was already set but I don't know where or how that was done.</p>
|
<p>I've sorted this out. <em>IF</em> I include my own heating commands in my start G-Code, Cura knows to NOT add its own heating commands at the start of the G-Code file.</p>
<p>The variables I was referring to have dedicated names.
<code>material_print_temperature_layer_0</code> is the printing (extruder/nozzle) temp set under Material in Cura.
<code>material_bed_temperature_layer_0</code> is the build plate temp set under Material in Cura.</p>
<p>Cura substitutes the values of those variables for the variable names in the G-code file.</p>
<p>So to avoid filament ooze during auto bed leveling, I set the nozzle temp to 150 °C (hot, but lower than the defined printing temp and low enough to avoid ooze). I set the bed temp to its defined temp.</p>
<p>Then I auto-level the bed.</p>
<p>Then I heat the nozzle up to its defined printing temp and start the print job.</p>
<p>This is my Start G-code:</p>
<pre><code>; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
M104 S150 ; Set Extruder temperature for bed leveling
M140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature
M109 S150 ; Wait for Extruder temperature for bed leveling
M190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature
G29 ; Auto Bed Level (CR Touch)
M104 S{material_print_temperature_layer_0} ; Set Extruder temperature
M109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X5 Y20 Z0.3 F5000.0 ; Move over to prevent blob squish
</code></pre>
<p>And this is how Cura writes the G-code file:</p>
<pre><code>;FLAVOR:Marlin
;TIME:2888
;Filament used: 1.96332m
;Layer height: 0.2
;MINX:93.266
;MINY:10.195
;MINZ:0.2
;MAXX:126.734
;MAXY:210.658
;MAXZ:4.2
;Generated with Cura_SteamEngine 4.13.1
M82 ;absolute extrusion mode
; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
M104 S150 ; Set Extruder temperature for bed leveling
M140 S60 ; Set Heat Bed temperature
M109 S150 ; Wait for Extruder temperature for bed leveling
M190 S60 ; Wait for Heat Bed temperature
G29 ; Auto Bed Level (CR Touch)
M104 S200 ; Set Extruder temperature
M109 S200 ; Wait for Extruder temperature
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X5 Y20 Z0.3 F5000.0 ; Move over to prevent blob squish
G92 E0
...
</code></pre>
<p>I hope this helps someone with a similar question.</p>
<p>Cheers.</p>
|
<p>Go to the <code>Settings</code> -> <code>Printers</code> menu from the top menu,</p>
<p><a href="https://i.stack.imgur.com/jmivX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jmivX.png" alt="enter image description here" /></a></p>
<p>select your active printer (or <code>Activate</code> it) and manage your printer trough <code>Machine Settings</code>.</p>
<p><a href="https://i.stack.imgur.com/L3CUC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L3CUC.png" alt="enter image description here" /></a></p>
<p>It will open the printer settings,</p>
<p><a href="https://i.stack.imgur.com/rBjqg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rBjqg.png" alt="enter image description here" /></a></p>
<p>there you are able to change the lines you want in the <code>Start G-code</code> section.</p>
<p>Note the default Start G-code doesn't include heating up the bed and core, you need to add these after the <code>G29</code> in your case. Personally I use heat up bed and continue (<code>M140</code>), than heat up core and wait till temperature is reached (<code>M109</code>), then heat up and wait until bed temperature is reached (<code>M190</code>).</p>
| 2,152
|
<p>Am developing my web application using Django, and is seems CSS is the only way i can format my pages to look and feel nice. Where can i get a free and good css editor?</p>
<p>NB: Is there another way to format forms in Django?</p>
|
<p>Cool stuff for Eclipse...</p>
<p><a href="http://aptana.com/studio" rel="nofollow noreferrer">http://aptana.com/studio</a></p>
|
<p>There are other ways to format forms but CSS is the best way. I'll second the recommendation for Aptana, and according to Lifehacker <a href="http://lifehacker.com/5073005/css-toolbox-is-a-killer-text-editor-for-web-designers" rel="nofollow noreferrer">CSS Toolbox</a> is also quite good.</p>
| 32,634
|
<p>If you check my earlier questions you may have noticed I just don't get the SelectList and Html.DropDown(). I find it intrigueing that I seem to be the only one in this. So maybe I should try to change my mindset or maybe there are things I don't know that will clear this all up. I really love the whole MVC framework, but SelectList just doesn't want to fit in my head. So here's my list:</p>
<p><strong>SelectList</strong></p>
<ul>
<li>Why can't I set the selected value after instantiation</li>
<li>Why can't I set selectedValue by index of items</li>
<li>Why is the selectedvalue sometimes a string, sometimes the class I put into it and sometimes a ListItem</li>
<li>Why are the items only accesible through GetItems()</li>
<li>Why don't the types of selectedItem and the listItems match?</li>
<li>Why are the items you put in the list converted to listItem and the selectedItem not?</li>
<li>Why can't I get the count of the items without usint the GetItems() method</li>
</ul>
<p><strong>Html.DropDownList()</strong></p>
<ul>
<li>Why doesn't modelbinding work with it</li>
<li>Why is there no behaviour for defaulting selection when there's only one option </li>
<li>Why doesn't making an item SelectedValue in the source selectLIst make it the marked item</li>
</ul>
<p>Before ppl suggest me to write my own:<br>
Since this will be shipped with the MVC product, I would rather have the offical support for a basic controll then to roll my own and have all the troubles that come with it.</p>
|
<p>I feel your pain. Forgive the shameless plug, but you might look into <a href="http://lunaverse.wordpress.com/2008/11/24/mvcfluenthtml-fluent-html-interface-for-ms-mvc/" rel="nofollow noreferrer">MvcFluentHtml</a>. You can still use SelectList and MultiSelectList, but you have several other choices. Should work fine with binders.</p>
|
<p>I feel your pain. Forgive the shameless plug, but you might look into <a href="http://lunaverse.wordpress.com/2008/11/24/mvcfluenthtml-fluent-html-interface-for-ms-mvc/" rel="nofollow noreferrer">MvcFluentHtml</a>. You can still use SelectList and MultiSelectList, but you have several other choices. Should work fine with binders.</p>
| 43,664
|
<p>I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style.</p>
<p>Any ideas about how to detect which mode the user is in and re-format the forms on the fly?</p>
<hr>
<p>Post Answer Edit:</p>
<p>Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function.</p>
<p>I'm doing the following:</p>
<p><strong>Function Declaration:</strong>
<pre><code> Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32
</pre></code></p>
<p><strong><em>Code Body:</em></strong>
<pre><code>
Dim stringThemeName As New System.Text.StringBuilder(260)
Dim stringColorName As New System.Text.StringBuilder(260)
Dim stringSizeName As New System.Text.StringBuilder(260)</p>
<p>GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260)
MsgBox(stringThemeName.ToString)
</pre></code></p>
<p>The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue.</p>
|
<p>Try using a combination of <a href="http://www.pinvoke.net/default.aspx/uxtheme/GetCurrentThemeName.html" rel="nofollow noreferrer">GetCurrentThemeName</a> (<a href="http://msdn.microsoft.com/en-us/library/bb773365%28VS.85%29.aspx" rel="nofollow noreferrer">MSDN Page</a>) and <a href="http://msdn.microsoft.com/en-us/library/aa969518%28VS.85%29.aspx" rel="nofollow noreferrer">DwmIsCompositionEnabled</a></p>
<p>I linked the first to PInvoke so you can just drop it in your code, and for the second one you can use the code provided in the MSDN comment:</p>
<pre><code>[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
</code></pre>
<p>See what results you get out of those two functions; they should be enough to determine when you want to use a different theme!</p>
|
<p>There's the <a href="http://msdn.microsoft.com/en-us/library/bb759813%28VS.85%29.aspx" rel="nofollow noreferrer">IsThemeActive</a> WinAPI function.</p>
| 5,506
|
<p>The code</p>
<pre><code><%=Html.CheckBox("SendEmail") %>
</code></pre>
<p>evaluates to two HTML elements when it's rendered</p>
<pre><code><input id="SendEmail" name="SendEmail" type="checkbox" value="true" />
<input name="SendEmail" type="hidden" value="false" />
</code></pre>
<p>Is this by a bug? Or by design? If it's by design, why?</p>
|
<p>I was having some trouble this morning with retrieving selected values from a checkbox group in my MVC app. I sent this out to my team and thought I'd share it with everyone else.</p>
<p>When posting back values for checkboxes, the standard behaviour of all browsers is to completely leave out un-checked checkboxes from the post back. So if you have a checkbox that isn’t checked then nothing shows up for this in Request.Form. This is a fairly well-known phenomenon that most developers account for.</p>
<p>In ASP.Net MVC when you use Html.Checkbox, it attempts to get around this and ensure that you have a value posted back (in this case ‘false’) for un-checked checkboxes. This is done by adding a hidden field containing the value ‘false’.</p>
<p>Eg.</p>
<pre><code><%= Html.CheckBox("Sites", s.Selected, new { value = s.Value })%>
</code></pre>
<p>Produces the HTML</p>
<pre><code><input id="Sites" name="Sites" type="checkbox" value="1" /><input name="Sites" type="hidden" value="false" />
</code></pre>
<p>This is all good and well, until you attempt to use checkbox groups. That is more than one checkbox with the same name where the values are sent back in a single comma separated string.
MVC can split this string up for you automatically if you define the value as an array (string[] Sites).</p>
<p>Here’s the view code:</p>
<pre><code><% foreach(var s in Model) { %>
<li><%= Html.CheckBox("Sites", s.Selected, new { value = s.Value })%>
<label><%= s.Name %></label>
</li>
<% } %>
</code></pre>
<p>The appropriate controller action:</p>
<p>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int Id, string Name, string SubmissionUrl, string[] Sites)</p>
<p>Unfortunately, because the Html.Checkbox produces this hidden field value as well, the resulting array contains not only values for the selected checkboxes but also ‘false’ for every un-checked checkbox. You get an array that looks something like this:</p>
<pre><code>[0] 'false'
[1] 'false'
[2] '110'
[3] '50'
[4] 'false'
</code></pre>
<p>Where 'false' is for checkboxes that are not selected, and integers are the values for the checkboxes that are selected.</p>
<p>This can throw your code out quite a bit if you have only integers for the values of your checkboxes and want to define the result as an array of integers, like so:</p>
<p>public ActionResult Edit(int Id, string Name, string SubmissionUrl, int[] Sites)</p>
<p>Which results in an exception being thrown because it can’t convert the string value ‘false’ to an integer. </p>
<p>The solution is very simple, just avoid Html.Checkbox and manually create the checkboxes in your view code like this:</p>
<pre><code> <% foreach(var s in Model) { %>
<li><input type="checkbox" name="Sites" value="<%=s.Value%>" <% if (s.Selected) { %>checked="checked"<% } %> />
<label><%= s.Name %></label>
</li>
<% } %>
</code></pre>
<p>Hope this helps someone else!</p>
|
<p>I think I found <a href="http://forums.asp.net/p/1314753/2603373.aspx" rel="nofollow noreferrer">something on the web</a> that is directly related to my question.</p>
| 48,843
|
<p>How can I monitor the memory being used by a native C DLL that is being called from Java via JNI? Using standard Java monitoring tools and options I can see the Java memory space, but I cannot view any memory used by the C DLL. Java is using ~70MB, but the task in the Task Manager shows 200Mb+, and I'd like to see what's in that 130MB extra if possible.</p>
|
<p>You can monitor the native heap with counters in the performance montitor. (perfmon32) however it wont break it down for you on a per DLL basis, even jvm.dll will be included here.</p>
<p>Most profiling tools out there can attach to a process and capture and track memory allocations and deallocations. This allows them to speculate where leaks are.
One pretty good one i found when recently trying to track down memory leaks in native code which was called from Java is <a href="http://www.softwareverify.com/cpp/memory/index.html" rel="nofollow noreferrer">Memory Validator</a></p>
|
<p>I believe even doing this inside the C DLL would not be very easy. </p>
<p>As far as I understand the Standard Java Monitoring tools gather information by querying the Virtual Machine, thus even though that memory is in the same process unless the virtual machine knows how to inspect your dynamically linked library, it won't be able to see anything. I believe you would need to use an external tool or make somewhat massive modifications to the DLL in order to track its memory usage.</p>
| 22,352
|
<p>I'm working on a site that involves displaying a ton of product images from a variety of online retailers. Since most of the page weight is in the images, I thought it'd be worth looking into techniques for trimming down the file size a bit more. </p>
<p>The images are already JPEGs. I know PNGs have a lot of extra cruft that can balloon the file size considerably, but I have less experience with JPEGs. So, a couple related questions:</p>
<ol>
<li><p>Is it worth further compressing the JPEGs?
Seems like further compressing something that's already in a lossy format could lead to more harm (poor quality) than good (saving 10+% on the file size).</p></li>
<li><p>Are there other techniques to reducing the filesize?
I don't know if the EXIF metadata or other metadata are a part of any of these images, and if cutting those is a substantial improvement.</p></li>
<li><p>Any experience / recommendations for using GD or ImageMagick (or something else?)
There's also commercial image compression library from a company called Spinwave.</p></li>
</ol>
|
<p>Do you use thumbnail images? If so, are they saved separately or is the larger image loaded in full and just resized on the webpage? Having separate thumbnails sized as you're displaying them on your pages will save a lot of bandwidth. </p>
<p>You can decrease the quality factor on the JPEGs until you can see it. You'll see an improvement in the file size each time you do this. However, as you suspect, since you already have JPEGs, you may see the checkerboarding artifacts in the images sooner because you're compressing already-compressed images.</p>
<p>GD or IM both work well.</p>
|
<ul>
<li><p>There are lossless compresions like .ZIP but they are usually worse and not very usefull for an already compresed format.</p></li>
<li><p>JPEG can have diferent levels of compression. It's your decision how much quality is just enough. A photo from a digital camera can be compressed un one tenth it's size while perfectly suitable for a website.</p></li>
<li><p>JPEG is better for photographs. PNG is better for logos and plain colors. </p></li>
<li><p>ImageMagick should allow you to change sizes of a jpeg from command line or a program lib.
See <a href="http://www.imagemagick.org/Usage/formats/#jpg" rel="nofollow noreferrer">http://www.imagemagick.org/Usage/formats/#jpg</a></p></li>
</ul>
| 31,411
|
<p>Say you have several webparts, one as a controller and several which take information from the controller and act on it. This is fairly easy to model using the Consumer/Producer interface introduced in ASP 2.0. </p>
<p>How would you be able to add interactions the other way around whilst still maintaining the above? </p>
<p>A simple example would be: the user enters information into webpart A which performs a search and the results would be displayed on webpart B. Webpart C allows you to filter the results which should trigger webpart A to re-submit the query and hence update the results in B. </p>
<p>It doesn't seem possible to do in WSS 3.0 because you are only allowed 1 interface to be used in all of the connections at any one time. </p>
<p>Does this even make sense ? :-)</p>
|
<p>A quick and dirty solution to enable arbitrary control communication is to use recursive find control and events. Have the controls search the control tree by control type for what they need and then subscribe to publicly exposed events on the publishing control. </p>
<p>I have previous used the trick to enable standard server controls to find each other when embedded in CMS systems from different vendors to avoid a specific communication API entirely.</p>
|
<p>I don't see anything wrong with webpart A getting a reference to webpart B and calling public/internal methods/properties or subscribing handlers to public/internal events. One point of mention when doing this though: EnsureChildControls. I have witnessed with my own eyes one webpart being run clear to PreRender while another webpart hadn't even run CreateChildControls. </p>
<p>From webpart A, fetch your reference to webpart B (in this case webpart B is of type Calendar) like so:</p>
<pre><code> private Calendar _calendarWP = null;
public Calendar CalendarWP
{
get
{
if (_calendarWP != null)
return _calendarWP;
else
foreach (System.Web.UI.WebControls.WebParts.WebPartZone zone in this.WebPartManager.Zones)
foreach (System.Web.UI.WebControls.WebParts.WebPart webpart in zone.WebParts)
if (webpart is Calendar)
{
_calendarWP = (Calendar)webpart;
_calendarWP.EnsureChildControls();
return _calendarWP;
}
return null;
}
}
</code></pre>
<p>Now you can do things like fetch some new data and update the Calendar like so:</p>
<pre><code> IEnumerable newData = SomeDataProvider.GetNewData(args);
CalendarWP.someGridView.DataSource = newData;
CalendarWP.someGridView.DataBind();
</code></pre>
<p>Or perhaps let webpart A toss a reference to itself over to webpart B so it can use webpart A's public/internal properties to go fetch data for itself:</p>
<pre><code>CalendarWP.UseWPAToFetchData(this);
</code></pre>
| 19,066
|
<p>I have a SQL database (SQL Server 2008) which contains the following design</p>
<h2>ITEM</h2>
<ul>
<li>ID (Int, Identity)</li>
<li>Name (NVarChar(50))</li>
<li>Description (NVarChar(200))</li>
</ul>
<h2>META</h2>
<ul>
<li>ID (Int, Identity)</li>
<li>Name (NVarChar(50))</li>
</ul>
<p>There exists a N-N relationship between these two, i.e an Item can contain zero or more meta references and a meta can be associated with more than one item. Each meta can only be assocated with the same item once. This means I have the classic table in the middle</p>
<h2>ITEMMETA</h2>
<ul>
<li>ItemID (Int)</li>
<li>MetaID (Int)</li>
</ul>
<p>I would like to to execute a LinqToSql query to extract all of the item entities which contains a specific set of meta links. For example, give me all the Items which have the following meta items associated with it</p>
<ul>
<li>Car</li>
<li>Ford</li>
<li>Offroad</li>
</ul>
<p>Is it possible to write such a query with the help of LinqToSql? Let me provide some more requirements</p>
<ul>
<li>I will have a list of Meta tags I want to use to filter the items which will be returned (for example in the example above I had Car, Ford and Offroad)</li>
<li>An item can have MORE meta items associated with it than what I provide in the match, i.e if an item had Car, Ford, Offroad and Red assocated to it then providing any combination of them in the filter should result in a match</li>
<li>However ALL of the meta names which are provided in the filter MUST be assocated with an item for it to be returned in the resultset. So sending in Car, Ford, Offroad and Red SHOULD NOT be a match for an item which has Car, Ford and Offroad (no Red) associated with itself</li>
</ul>
<p>I hope its clear what I'm trying to achieve, I feel Im not being quite as clear as I'd hoped =/ Let's hope its enough :)</p>
<p>Thank you!</p>
|
<p>This should work for you:</p>
<pre><code>string[] criteria = new[] { "Car", "Ford", "Offroad" };
var items =
from i in db.Item
let wantedMetas = db.Meta.Where(m => criteria.Contains(m.Name))
let metas = i.ItemMeta.Select(im => im.Meta)
where wantedMetas.All(m => metas.Contains(m))
select i;
</code></pre>
<p>Basically it compares the "wanted" metas against each item's metas, and selects the items which have all the wanted metas (or more).</p>
|
<p>this brings back anything that matchs any of the meta criteria, and then filters it down to only things that match all the criteria. (also, keep in mind that you'll need to have your relationship defined in your datacontext). Let us know if you need clarification.</p>
<pre><code>var db = new YourDataContext();
var possibleItems = (from m in db.Metas where <meta criteria> select m.ItemMetas.Item);
var items = possibleItems.GroupBy(y=>y).Where(x=>x.Count() == criteriaCount).Select(x=>x.Key);
</code></pre>
| 31,355
|
<p>How do you return 1 value per row of the max of several columns:</p>
<p><strong>TableName</strong></p>
<pre><code>[Number, Date1, Date2, Date3, Cost]
</code></pre>
<p>I need to return something like this:</p>
<pre><code>[Number, Most_Recent_Date, Cost]
</code></pre>
<p>Query?</p>
|
<p>Here is another nice solution for the <code>Max</code> functionality using T-SQL and SQL Server</p>
<pre><code>SELECT [Other Fields],
(SELECT Max(v)
FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate]
FROM [YourTableName]
</code></pre>
<p>Values is the <a href="https://learn.microsoft.com/en-us/sql/t-sql/queries/table-value-constructor-transact-sql?view=sql-server-ver15" rel="noreferrer">Table Value Constructor</a>.</p>
<p>"Specifies a set of row value expressions to be constructed into a table. The Transact-SQL table value constructor allows multiple rows of data to be specified in a single DML statement. The table value constructor can be specified either as the VALUES clause of an INSERT ... VALUES statement, or as a derived table in either the USING clause of the MERGE statement or the FROM clause."</p>
|
<p>here is a good solution:</p>
<pre><code>CREATE function [dbo].[inLineMax] (@v1 float,@v2 float,@v3 float,@v4 float)
returns float
as
begin
declare @val float
set @val = 0
declare @TableVal table
(value float )
insert into @TableVal select @v1
insert into @TableVal select @v2
insert into @TableVal select @v3
insert into @TableVal select @v4
select @val= max(value) from @TableVal
return @val
end
</code></pre>
| 9,644
|
<p>i have two servers a main site and a static server.
i want to get a file's content from ajax in runtime, which is stored in static server.
obviously cross domain problem will occur.</p>
<p>so what i am trying to do is storing that ajax .js in the static server, so that calling the local file wont be a problem.</p>
<p>but after i include that js file from static, still that problem remains...</p>
<p>Any solutions?!</p>
|
<p>This might be a stretch, but check one of php's number one confusions with relative path resolution. </p>
<pre><code>'./'
</code></pre>
<p>is relative to wherever Entrypoint is, not the script, which is why I use </p>
<pre><code>dirname(__FILE__).'/'
</code></pre>
<p>everywhere instead. </p>
|
<p>Are you sure the path to <code>info.xml</code> is correct? That gets me sometimes when I am including a file from a subdirectory.</p>
| 39,137
|
<p>I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand.</p>
<p>The code is sorta like the following in structure:</p>
<pre><code><?php
$lots of = "php";
?>
<xml>
<morexml>
<?php
while(){
?>
<somegeneratedxml>
<?php } ?>
<lastofthexml>
<?php ?>
<html>
<pre>
The XML for the user to preview
</pre>
<form>
<input id="xml" value="theXMLagain" />
</form>
</html>
</code></pre>
<p>My XML is being generated with a few while loops and stuff. It then needs to be shown in the two places (the preview and the form value). </p>
<p>My question is. How do I capture the generated XML in a variable or whatever so I only have to generate it once and then just print it out as apposed to generating it inside the preview and then again inside the form value?</p>
|
<pre><code><?php ob_start(); ?>
<xml/>
<?php $xml = ob_get_clean(); ?>
<input value="<?php echo $xml ?>" />͏͏͏͏͏͏
</code></pre>
|
<p>You could try this:</p>
<pre><code><?php
$string = <<<XMLDoc
<?xml version='1.0'?>
<doc>
<title>XML Document</title>
<lotsofxml/>
<fruits>
XMLDoc;
$fruits = array('apple', 'banana', 'orange');
foreach($fruits as $fruit) {
$string .= "\n <fruit>".$fruit."</fruit>";
}
$string .= "\n </fruits>
</doc>";
?>
<html>
<!-- Show XML as HTML with entities; saves having to view source -->
<pre><?=str_replace("<", "&lt;", str_replace(">", "&gt;", $string))?></pre>
<textarea rows="8" cols="50"><?=$string?></textarea>
</html>
</code></pre>
| 20,655
|
<p>I've been trying to install PDT in Eclipse 3.4 for a few hours now and I'm not having any success.</p>
<p>I have a previous installation of the Eclipse for Java EE developers (my main deal) distro and I just want to add the PDT to my install so I can also work on some of my websites in Eclipse. </p>
<p>I've done my best to follow <a href="http://wiki.eclipse.org/PDT/Installation" rel="nofollow noreferrer">the instructions</a> at the PDT Wiki and I'm just not having any success. The specific message that it barks at me when I attempt to select the <strong>PDT Features</strong> option in the PDT Update Site section of the available software dialog is thus: </p>
<pre><code>Cannot complete the request. See the details.
Cannot find a solution satisfying the following requirements Match[requiredCapability:
org.eclipse.equinox.p2.iu/org.eclipse.wst.web_ui.feature.feature.group/
[3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF,
3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF]].
</code></pre>
<p>What is the solution?</p>
|
<p>If you have a list of all the plugins that you already have it may be faster and easier to go to <a href="http://www.yoxos.com/ondemand/" rel="nofollow noreferrer">YOXOS</a> and download a new copy of eclipse with all the plugins already loaded. just remember to change your workspace if you do this.</p>
|
<p>I have looked at lots of guides, but i finaly figured it out on myself:</p>
<ol>
<li>Download Ganyamede SDK</li>
<li>Through update manager install Web Developer Tools ( v 3.0.x )</li>
<li>Again using update manager instal DLTK version 1.0 or higher</li>
<li><p>manualy download latest integration or nightly od PDT 2.0 and unpack it in eclipse folder</p></li>
<li><p>and now you should have working PDT 2.0 in ganyamede ;)</p></li>
</ol>
| 12,289
|
<p>Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.</p>
<p>Particular order doesn't matter much here.</p>
<p>I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.</p>
|
<pre><code>#include <stdint.h>
#include <stdio.h>
union ui64 {
uint64_t one;
uint16_t four[4];
};
int
main()
{
union ui64 number = {0x123456789abcdef0};
printf("%x %x %x %x\n", number.four[0], number.four[1],
number.four[2], number.four[3]);
return 0;
}
</code></pre>
|
<pre><code>union LongLongIntToThreeUnsignedShorts {
long long int long_long_int;
unsigned short int short_ints[sizeof(long long int) / sizeof(short int)];
};
</code></pre>
<p>That should do what you are thinking about, without having to mess around with bit shifting.</p>
| 17,862
|
<p>The build machine at work has many projects, but we are only experiencing a problem with one. </p>
<p>Two projects are very similar, one builds in debug mode, the other in release mode. They both clear out the projects directory, and then does a full Get from source safe. The debug build gets the source fine and fairly quickly, but the release build takes ages to get the source (It pauses for a long time on the CheckingModifications part, whereas the debug build does not pause for nearly as long). The sourcecontrol blocks are identical (included from a single file), and are as follows:</p>
<pre><code><sourcecontrol type="vss" autoGetSource="true" applyLabel="false">
<executable>C:\Program Files\Microsoft Visual Studio\VSS\win32\SS.EXE</executable>
<project>$/Projects</project>
<username>####</username>
<password>####</password>
<ssdir>\\####\SourceCode\VSS</ssdir>
<workingDirectory>D:\Projects\</workingDirectory>
<culture>en-GB</culture>
<cleanCopy>True</cleanCopy>
</sourcecontrol>
</code></pre>
<p>Any one have any ideas on why the release builds source control block is slower?</p>
|
<p>In the end we have switched from SourceSafe to SourceGear Vault (mainly for branching features, but speed and reliability were also large factors).</p>
<p>We have also moved our build machine from an old pc to a server which has a 1Gb/s connection to the source server, rather than 100Mb/s, which has helped considerably.</p>
<p>In the end when I was installing and testing Vault on the same machine (well, a clone) as the old build machine, it was cutting the source get operation from around 10 mins to 5. Once it was installed on the build server source get time is now around 1min.</p>
<p>My advice to anyone is just to switch from SourceSafe to anything else...you wont regret it.</p>
|
<p>Are the Debug and Release builds running at the same time? If so, I could see one waiting for the other to finish.</p>
| 32,790
|
<p>I'm trying to verify if a schema matches the objects I'm initializing.</p>
<p>Is there a way to get the TableName of a class other than simply reflecting the class name?</p>
<p>I am using some class with explicit TableNames</p>
<p>Edit: using Joe's solution I added the case where you don't specify the table name, it could probably use a constraint</p>
<pre><code>public string find_table_name(object obj)
{
object[] attribs = obj.GetType().GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);
if (attribs != null)
{
ActiveRecordAttribute attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
if (attrib.Table != null)
return attrib.Table;
return obj.GetType().Name;
}
return null;
}
</code></pre>
|
<p>If you have something like the following:</p>
<pre><code>[ActiveRecord(Table = "NewsMaster")]
public class Article
{
[PrimaryKey(Generator = PrimaryKeyType.Identity)]
public int NewsId { get; set; }
[Property(Column = "NewsHeadline")]
public string Headline { get; set; }
[Property(Column = "EffectiveStartDate")]
public DateTime StartDate { get; set; }
[Property(Column = "EffectiveEndDate")]
public DateTime EndDate { get; set; }
[Property]
public string NewsBlurb { get; set; }
}
</code></pre>
<p>This will get you the table name:</p>
<pre><code> [Test]
public void Can_get_table_name()
{
var attribs = typeof(Article).GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);
if (attribs != null)
{
var attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
Assert.AreEqual("NewsMaster", attrib.Table);
}
}
</code></pre>
|
<p>You could also use:</p>
<pre><code>ActiveRecordModel.GetModel(typeof(Article)).ActiveRecordAtt.Table
</code></pre>
<p>see <a href="http://svn.castleproject.org:8080/svn/castle/trunk/ActiveRecord/Castle.ActiveRecord.Tests/PluralizationTestCase.cs" rel="nofollow noreferrer">this testcase</a></p>
| 24,134
|
<p>I installed Aptana Studio plugins for Eclipse and now Eclipse startup is slower than ever because Aptana Studio always checks for updates at startup -- and it's really slow! </p>
<p>How do I turn off auto updates in Aptana? </p>
|
<p>Window->Preferences, find the Install/Update item in the tree and locate Automatic Updates. You can change the update behavior here.</p>
|
<p>For Aptana updates go to Window->Preferences. Then open the Aptana->Install/Update->Automatic_Updates preference panel. Once there deselect the "Automatically find new updates and notify me" check box.</p>
| 48,663
|
<p>How many messages does the queue for a standard window hold? What happens when the queue overflows?</p>
<p>The documentation for <code>GetMessage</code> and relatives doesn't say anything about this, and <code>PeekMessage</code> only gives you a yes/no for certain classes of messages, not a message count.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa925082.aspx" rel="noreferrer">This page</a> says that the queues are implemented using memory-mapped files, and that there is no message count limit, but that page is about WinCE. Does this apply to desktop Win32 as well?</p>
|
<p>10000 by default, but it can be adjusted via the registry.</p>
<p>If queue overflows, PostMessage fails.</p>
<p>Documentation here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms644944.aspx" rel="noreferrer"><code>PostMessage</code> function on MSDN</a></p>
|
<p>As stated in the MSDN article, if you need to worry about the size of the message queue, you might be better off redesigning your application.</p>
| 15,005
|
<p>I've got an application that just shipped. Since I wrote it, I've learned about amfphp and propel. Both would be 'nice' to be used in the application but I can't say that it would be required at this point.</p>
<p>What types of things do you consider before you refactor code?</p>
|
<p>Have unit tests to check the code after refactoring. </p>
|
<p>Create a fork for the current production code base in your source control and do all the refactoring in the experimental branch of the source control.</p>
| 49,724
|
<p>English is not my mother tongue. However, I have to write comments in English. I want to improve my "comment English" by studying a piece of code which is commented in a good English. Please recommend an open source project which contains a lot of meaningful comments written by people with an excellent command of the language.</p>
|
<p>I can recommend Simon Tatham's Puzzle Collection.</p>
<p>The comments I've read look like correct English to me. Also, they're clearly written and contain useful information about why things are done the way they are.</p>
<p>The developer documentation is also easy to read and understand, and as a side benefit you'll be reading the documentation of a system with a good and simple architecture.</p>
<p>If you aim to read something and then emulate it without explicitly understanding why doing so is a good idea, I can definitely recommend ST's puzzles. If you want an explicit understanding of what good writing is, I think ST's puzzles will serve as a good <em>example</em>, but you really want to read something like Strunk and White.</p>
|
<p>I've only ever looked at small pieces of it, but I hear the linux kernel is very well commented.</p>
| 30,865
|
<p>What is the best way to survey and detect bad users behavior or attacks like deny of services or exploits on my web app ?</p>
<p>I know server's statistics (like <a href="http://awstats.sourceforge.net/" rel="nofollow noreferrer">Awstats</a>) are very useful for that kind of purpose, specially to see 3XX, 4XX and 5XX errors (<a href="http://www.nltechno.com/awstats/awstats.pl?config=destailleur.fr&framename=mainright#errors" rel="nofollow noreferrer">here's an Awstats example page</a>) which are often bots or bad intentioned users that try well-known bad or malformed URLs.</p>
<p>Is there others (and betters) ways to analyze and detect that kind of attack tentative ?</p>
<p>Note : I'm speaking about URL based attacks, not attacks on server's component (like database or TCP/IP).</p>
|
<p>Log everything. Then examine the logs by hand, and find things that are uninteresting and write a parser that discards those log entries. Once you've done that, rinse and repeat until you're left with just the interesting things. Now that you have only interesting log entries to read, decide which ones are dangerous and which ones are harmless but annoying, and fix as appropriate.</p>
|
<p>More network as a whole but SATAN is very good</p>
<p><a href="http://www.porcupine.org/satan/" rel="nofollow noreferrer">http://www.porcupine.org/satan/</a></p>
<p>SATAN is a tool to help systems administrators. It recognizes several common networking-related security problems, and reports the problems without actually exploiting them.</p>
| 16,762
|
<p>I am working on a small project with a few friends and need to set up a server to run our tools. I looked around at hosted solutions like <a href="http://unfuddle.com/" rel="nofollow noreferrer">Unfuddle</a> but they don't provide a CI server.</p>
<p>I am now considering buying a <a href="http://www.linode.com/" rel="nofollow noreferrer">Linode</a> and running the following on it:</p>
<ul>
<li>Mail : <a href="http://james.apache.org/" rel="nofollow noreferrer">Apache JAMES</a> </li>
<li>CI : <a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a> </li>
<li>Wiki/Tracker : <a href="http://trac.edgewall.org/" rel="nofollow noreferrer">Trac</a> </li>
<li>Project Management: <a href="http://studios.thoughtworks.com/mingle-agile-project-management" rel="nofollow noreferrer">Mingle</a> </li>
<li>VCS : <a href="http://subversion.tigris.org/" rel="nofollow noreferrer">SVN</a></li>
</ul>
<p>I am a Linux server newbie, so does anyone have any writeups, advice etc about this? I am aware of <a href="http://buildix.thoughtworks.com/" rel="nofollow noreferrer">Buildix</a>, but they don't provide the combination I need. </p>
|
<p>I'm not sure how much power you need, but what I've done in the past is grabbed an old desktop computer. Wiped the hard drive and installed an appropriate OS and then loaded my tools on that.</p>
<p>I setup port forwarding on my router to send incoming requests to it. And I got my hands a dynamic IP address URL (there are free and pay-for ones) and setup tools to always update the current IP address on the URL.</p>
<p>It worked great, was cheap and I learned a lot about server administration.</p>
<p>Yes, setup is harder and it takes longer but if you run this project for 12 months and you are paying (say $30 a month) then you save yourself $360 plus you gained a whole lot of insight in to Admin-ing Linux(or the OS of your choice).</p>
<p>Best Regards,<br>
Frank</p>
|
<p>If you have Ruby installed, you can pull down the <a href="http://www.deprec.org/" rel="nofollow noreferrer" title="Deprec2">deprec gem</a> ("deprec" is for "deploy recipe", not "deprecated"). It's geared toward Rails, but will set up Trac and source control and let you perform other admin tasks. It may or may not be suitable to your needs, but I'd advise you to check it out.</p>
<p>Of course, choosing a distro with a robust package management system will help with installing commodity stuff.</p>
<p>As for mail, I'm not sure why you'd choose to run your own, when <a href="http://www.google.com/apps/intl/en/business/index.html" rel="nofollow noreferrer" title="Google Apps for Domains">Google will do it for you for free</a>. (Exception: If your app needs intimate access to mail, it might be simpler to run your own.)</p>
| 41,129
|
<p>I'm trying to run a command-line process (which is extraction of a .7z archive) on a file that lies in a temporary folder on the windows user temp directory
(C:\Documents and Settings\User\Local Settings\Temp), using Process in my c# app.</p>
<p>I think the process return error that happens because of "access denied" because I can see a win32Exception with error code 5 when I dig in the prcoess object of .NET.</p>
<p>doing the same on some other location worked fine before, so I guess maybe it's something I'm not supposed to do ? (running a process to use a file on the the %TEMP%)
perhaps I need to pass security somehow?</p>
|
<p>Assuming that you are using regular .NET (not CF/Silverlight, etc) Accessing files in the user's temp area is entirely expected. I wonder if the problem isn't more that you've accidentally left the file open after creating it, perhaps by not using a "using" or similar?</p>
<p>I probably wouldn't suggest using environment variables (%TEMP% etc) when shelling out to a separate process; ideally you'd pass the full path to the file (less things to get wrong...), making sure to <em>quote</em> any path arguments (in case of space) - i.e. so your args are @"... ""c:\some path\whatever\tmp""..." (if you see what I mean).</p>
<p>Finally, if you are extracting files, you need to think about the existing contents. <code>Path.GetTempFileName()</code> is fine for creating a single file place-holder, but for extracting an archive you probably want to create a directory - guids are handy for this purpoes (while avioding conflicts, and remember to remove it afterwards):</p>
<pre><code>string dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
</code></pre>
|
<p>running the same process using command-line (cmd) helped to figure out my problem was that I specified path arguments to the process using long-path-name.</p>
<p>Solution to this can be found here:</p>
<p><a href="https://stackoverflow.com/questions/258367/standard-way-to-convert-to-long-path-in-net">standard way to convert to short path in .net</a></p>
| 32,237
|
<p>Can anyone tell me what the need/advantage is to using a web service with an asp.net gui and using Linq to SQL? The web service layer seems unnecessary. Linq to SQL is completely new to me and I am researching as I am setting up a new project. Does anyone have any experience with this?</p>
|
<p>You would expose services for those cases in which other applications may need to access your data (such as a smart client, another application, a winforms app, etc.). A lot of people will develop using web services to prevent themselves from having to restructure to web services in the future.</p>
<p>In almost any professional/enterprise web application you want to separate the UI tier from the data access layer so you would not embed Linq to SQL calls in the UI tier. Instead you would have a service tier in between, whether its web services, WCF, or just a DLL with business logic that orchestrates your data access layer. Independent tiers are easier to maintain, update, refactor, and learn so the up front investment in creating them is worth the effort.</p>
|
<p>Agreed with previous poster. You'd probably want to do this to apply the "Separation of Concerns" idea...</p>
| 31,346
|
<p>I came across an issue that makes me think there is bug in the 3.0 framework. When I try to use extension methods I get the following error: </p>
<pre><code>Missing compiler required member
'System.Runtime.CompilerServices.ExtensionAttribute..ctor'
</code></pre>
<p>When using this simple code:</p>
<pre><code>public static class StringUtils {
static void TestExtension(this String targetString) {
}
}
</code></pre>
<p>The only way to make this compile error go away is to add the following code:</p>
<pre><code>namespace System.Runtime.CompilerServices {
public class ExtensionAttribute : Attribute { }
}
</code></pre>
<p>It's been a few months since I have used extensions methods, but I'm pretty sure I didn't have to do this. Has anyone else come across this issue?</p>
|
<p>I have the exact same problem. The error <code>System.Runtime.CompilerServices.ExtensionAttribute..ctor</code> is rather cryptic, and could mean a number of different things.</p>
<p>However, for me It boiled down to the fact that I'm using <code>Newtonsoft.Json.Net</code>. I removed the reference to the file <code>Newtonsoft.Json.Net20.dll</code>, and the re-added it. After this my solution builds again.</p>
<p>The strangest thing is that when I tried to find out what was different after this procedure by using Subversion Diff, nothing appears to have changed.</p>
<p>So I really don't know what removing and re-adding this reference really does, but it does fix my build issue with this particular error message mentioned by the asker.</p>
<h2><em>UPDATE 1</em>:</h2>
<p>For those that come across this again, as the comenters pointed out, the proper way to fix this is to <em><a href="http://json.codeplex.com/releases/view/50552" rel="nofollow noreferrer">Download Json.Net's ZIP</a>, and there should be a 3.5 version, re-reference 3.5 every where you are using Json.Net and delete the old reference, as it is likely referencing an assembly that was built for older versions of .net.</em></p>
<h2><em>UPDATE 2</em>:</h2>
<p><a href="https://stackoverflow.com/users/80112/charlie-flowers">Charlie Flowers</a> points out that the DLL NewtonSoft labels as being for 3.5 is actually not going to work with 3.5. You have to use the DLL they label as being for .net 2.0</p>
|
<p>Extensions are introduced in C# 3.0, which on the other hand was introduced in .NET 3.5 so you can't really use them in .NET 3.0 directly.</p>
| 25,194
|
<p>Here's the code:</p>
<pre><code>render :file => @somedir + "/blah.xml"
</code></pre>
<p>...but the resulting MIME type is text/html when I check in FireBug. How do I specify a MIME type in this case?</p>
|
<p>Actually there are two ways to set the content-type (I think this is what you mean by mime-type). You should use the second option, if it works for your Rails version.</p>
<pre><code>class FileController < ApplicationController
def index
filename = 'some.xml'
extname = File.extname(filename)[1..-1]
mime_type = Mime::Type.lookup_by_extension(extname)
content_type = mime_type.to_s unless mime_type.nil?
# 1
#headers['Content-Type'] = content_type
#render :file => filename
# 2
render :file => filename, :content_type => content_type
end
end
</code></pre>
<p>Hope this helps!</p>
|
<p>Per <a href="http://api.rubyonrails.org/classes/Mime/Type.html" rel="nofollow noreferrer">http://api.rubyonrails.org/classes/Mime/Type.html</a>, you could specify it like so:</p>
<pre><code>render file: @somedir + "/blah.xml", mime_type: Mime::Type.lookup("text/xml")
</code></pre>
| 38,454
|
<p>Is there any easier solution in porting a windows manual-reset event to pthread,
than a pthread conditional-variable + pthread mutex + a flag if event is set or unset?</p>
|
<p>Pthreads are low level constructs. No, there isn't a simpler mechanism; <code>pthread_cond__*</code> is conceptually similar to an auto-reset event. Be careful, <code>pthread_cond_wait</code> may have spurious wakeups, so it should never be used without some sort of external flag regardless of the situation.</p>
<p>Building your own wouldn't be too hard, though.</p>
<pre class="lang-c prettyprint-override"><code>#include <pthread.h>
#include <stdbool.h>
struct mrevent {
pthread_mutex_t mutex;
pthread_cond_t cond;
bool triggered;
};
void mrevent_init(struct mrevent *ev) {
pthread_mutex_init(&ev->mutex, 0);
pthread_cond_init(&ev->cond, 0);
ev->triggered = false;
}
void mrevent_trigger(struct mrevent *ev) {
pthread_mutex_lock(&ev->mutex);
ev->triggered = true;
pthread_cond_signal(&ev->cond);
pthread_mutex_unlock(&ev->mutex);
}
void mrevent_reset(struct mrevent *ev) {
pthread_mutex_lock(&ev->mutex);
ev->triggered = false;
pthread_mutex_unlock(&ev->mutex);
}
void mrevent_wait(struct mrevent *ev) {
pthread_mutex_lock(&ev->mutex);
while (!ev->triggered)
pthread_cond_wait(&ev->cond, &ev->mutex);
pthread_mutex_unlock(&ev->mutex);
}
</code></pre>
<p>This may not fit your usage, as you will often have a different lock that you'd want to use in place of <code>ev->mutex</code>, but this is the gist of how it's typically used.</p>
|
<p>We (full disclosure: I work at NeoSmart Technologies) wrote an open source (MIT licensed) library called <a href="https://github.com/NeoSmart/PEvents" rel="nofollow">pevents</a> which <a href="http://neosmart.net/blog/2011/waitformultipleobjects-and-win32-events-for-linux-and-read-write-locks-for-windows/" rel="nofollow">implements WIN32 manual and auto-reset events</a> on POSIX, and includes both WaitForSingleObject and WaitForMultipleObjects clones. It's seen some adoption since then (it's used in Steam on Linux/Mac) and works fairly well.</p>
<p>Although I'd personally advise you to use POSIX multithreading and signaling paradigms when coding on POSIX machines, pevents gives you another choice if you need it.</p>
| 21,459
|
<p>How can I reboot a Windows XP64 Machine in a Python Script? This machine does not have the "shutdown" or "restart" executables available.</p>
|
<p>found it </p>
<p>win32api.InitiateSystemShutdown("localhost", "Maintenance Reboot", 60, 1, 1)</p>
|
<p>You can use win32api module and call WinApi functions.
<a href="http://code.activestate.com/recipes/360649/" rel="nofollow noreferrer">Recipe at code.activestate.com</a></p>
| 44,326
|
<p>How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?</p>
|
<p>To read user input you can try <a href="https://docs.python.org/dev/library/cmd.html" rel="noreferrer">the <code>cmd</code> module</a> for easily creating a mini-command line interpreter (with help texts and autocompletion) and <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="noreferrer"><code>raw_input</code></a> (<a href="https://docs.python.org/dev/library/functions.html#input" rel="noreferrer"><code>input</code></a> for Python 3+) for reading a line of text from the user.</p>
<pre><code>text = raw_input("prompt") # Python 2
text = input("prompt") # Python 3
</code></pre>
<p>Command line inputs are in <code>sys.argv</code>. Try this in your script:</p>
<pre><code>import sys
print (sys.argv)
</code></pre>
<p>There are two modules for parsing command line options: <a href="https://docs.python.org/dev/library/optparse.html" rel="noreferrer"><s><code>optparse</code></s></a> (deprecated since Python 2.7, use <a href="https://docs.python.org/dev/library/argparse.html" rel="noreferrer"><code>argparse</code></a> instead) and <a href="https://docs.python.org/dev/library/getopt.html" rel="noreferrer"><code>getopt</code></a>. If you just want to input files to your script, behold the power of <a href="https://docs.python.org/dev/library/fileinput.html" rel="noreferrer"><code>fileinput</code></a>.</p>
<p>The <a href="https://docs.python.org/dev/library/" rel="noreferrer">Python library reference</a> is your friend.</p>
|
<p>In Python 2:</p>
<pre><code>data = raw_input('Enter something: ')
print data
</code></pre>
<p>In Python 3:</p>
<pre><code>data = input('Enter something: ')
print(data)
</code></pre>
| 9,629
|
<p>I want something similar to the following pseudocode:</p>
<pre><code>myGridView.SelectedIndex = myGridView.DataKeys.IndexOf("mySpecificKey");
</code></pre>
<p>I've done some Intellisense exploring, but I haven't found an obvious way to do this. I would want to set SelectedIndex to -1 if DataKey was not found.</p>
|
<p>I've ended up with</p>
<pre><code> For n As Integer = 0 To myGridView.DataKeys.Count - 1
If myGridView.DataKeys(n).Value = myKeyObj Then
myGridView.SelectedIndex = n
End If
Next
</code></pre>
|
<p>Put something like this in your GridView_RowDataBound() event:</p>
<pre><code>Dim p As Catalog.Product = CType(e.Row.DataItem, Catalog.Product)
If p IsNot Nothing Then
If p.Bvin = MySpecificID Then
e.Row.RowState = DataControlRowState.Selected
End If
End If
</code></pre>
<p>In this example, we are binding the GridView to a collection of custom objects of type Catalog.Product and the DataKey is named Bvin - you will need to adjust the datatype and key name depending on what you are binding to.</p>
<p>Note this event runs once per row already, so there is no need to loop. However, care should be taken to prevent things like data access from occurring more than once.</p>
| 45,616
|
<p>I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:</p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?</p>
<p><a href="http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html" rel="noreferrer">http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html</a></p>
|
<p>Well, you can make things a little easier by fixing up the syntax:</p>
<pre><code>def r(a):
i = a.find('0')
~i or exit(a)
[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import *
r(argv[1])
</code></pre>
<p>Cleaning up a little:</p>
<pre><code>from sys import exit, argv
def r(a):
i = a.find('0')
if i == -1:
exit(a)
for m in '%d' % 5**18:
m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)] or r(a[:i]+m+a[i+1:])
r(argv[1])
</code></pre>
<p>Okay, so this script expects a command-line argument, and calls the function r on it. If there are no zeros in that string, r exits and prints out its argument. </p>
<blockquote>
<p>(If another type of object is passed,
None is equivalent to passing zero,
and any other object is printed to
sys.stderr and results in an exit
code of 1. In particular,
sys.exit("some error message") is a
quick way to exit a program when an
error occurs. See
<a href="http://www.python.org/doc/2.5.2/lib/module-sys.html" rel="noreferrer">http://www.python.org/doc/2.5.2/lib/module-sys.html</a>)</p>
</blockquote>
<p>I guess this means that zeros correspond to open spaces, and a puzzle with no zeros is solved. Then there's that nasty recursive expression.</p>
<p>The loop is interesting: <code>for m in'%d'%5**18</code></p>
<p>Why 5**18? It turns out that <code>'%d'%5**18</code> evaluates to <code>'3814697265625'</code>. This is a string that has each digit 1-9 at least once, so maybe it's trying to place each of them. In fact, it looks like this is what <code>r(a[:i]+m+a[i+1:])</code> is doing: recursively calling r, with the first blank filled in by a digit from that string. But this only happens if the earlier expression is false. Let's look at that:</p>
<p><code>m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)]</code></p>
<p>So the placement is done only if m is not in that monster list. Each element is either a number (if the first expression is nonzero) or a character (if the first expression is zero). m is ruled out as a possible substitution if it appears as a character, which can only happen if the first expression is zero. When is the expression zero?</p>
<p>It has three parts that are multiplied:</p>
<ul>
<li><code>(i-j)%9</code> which is zero if i and j are a multiple of 9 apart, i.e. the same column.</li>
<li><code>(i/9^j/9)</code> which is zero if i/9 == j/9, i.e. the same row.</li>
<li><code>(i/27^j/27|i%9/3^j%9/3)</code> which is zero if both of these are zero:</li>
<li><ul>
<li><code>i/27^j^27</code> which is zero if i/27 == j/27, i.e. the same block of three rows</li>
</ul></li>
<li><ul>
<li><code>i%9/3^j%9/3</code> which is zero if i%9/3 == j%9/3, i.e. the same block of three columns</li>
</ul></li>
</ul>
<p>If any of these three parts is zero, the entire expression is zero. In other words, if i and j share a row, column, or 3x3 block, then the value of j can't be used as a candidate for the blank at i. Aha!</p>
<pre><code>from sys import exit, argv
def r(a):
i = a.find('0')
if i == -1:
exit(a)
for m in '3814697265625':
okay = True
for j in range(81):
if (i-j)%9 == 0 or (i/9 == j/9) or (i/27 == j/27 and i%9/3 == j%9/3):
if a[j] == m:
okay = False
break
if okay:
# At this point, m is not excluded by any row, column, or block, so let's place it and recurse
r(a[:i]+m+a[i+1:])
r(argv[1])
</code></pre>
<p>Note that if none of the placements work out, r will return and back up to the point where something else can be chosen, so it's a basic depth first algorithm.</p>
<p>Not using any heuristics, it's not particularly efficient. I took this puzzle from Wikipedia (<a href="http://en.wikipedia.org/wiki/Sudoku" rel="noreferrer">http://en.wikipedia.org/wiki/Sudoku</a>):</p>
<pre><code>$ time python sudoku.py 530070000600195000098000060800060003400803001700020006060000280000419005000080079
534678912672195348198342567859761423426853791713924856961537284287419635345286179
real 0m47.881s
user 0m47.223s
sys 0m0.137s
</code></pre>
<p>Addendum: How I would rewrite it as a maintenance programmer (this version has about a 93x speedup :)</p>
<pre><code>import sys
def same_row(i,j): return (i/9 == j/9)
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)
def r(a):
i = a.find('0')
if i == -1:
sys.exit(a)
excluded_numbers = set()
for j in range(81):
if same_row(i,j) or same_col(i,j) or same_block(i,j):
excluded_numbers.add(a[j])
for m in '123456789':
if m not in excluded_numbers:
# At this point, m is not excluded by any row, column, or block, so let's place it and recurse
r(a[:i]+m+a[i+1:])
if __name__ == '__main__':
if len(sys.argv) == 2 and len(sys.argv[1]) == 81:
r(sys.argv[1])
else:
print 'Usage: python sudoku.py puzzle'
print ' where puzzle is an 81 character string representing the puzzle read left-to-right, top-to-bottom, and 0 is a blank'
</code></pre>
|
<p>The code doesn't actually work. You can test it yourself. Here is a sample unsolved sudoku puzzle:</p>
<p>807000003602080000000200900040005001000798000200100070004003000000040108300000506</p>
<p>You can use this website (<a href="http://www.sudokuwiki.org/sudoku.htm" rel="nofollow">http://www.sudokuwiki.org/sudoku.htm</a>), click on import puzzle and simply copy the above string. The output of the python program is:
817311213622482322131224934443535441555798655266156777774663869988847188399979596</p>
<p>which does not correspond to the solution. In fact you can already see a contradiction, two 1s in the first row. </p>
| 24,598
|
<p>I want to impersonate other user in Windows. For example:
I create a directory with permission only for user A and for the administrators, when logon with user B and run .exe I want to impersonate user A to have permission to edit/remove/insert in that specific directory.</p>
<p>I found this: <a href="http://msdn.microsoft.com/en-us/library/aa374731(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa374731(VS.85).aspx</a></p>
|
<p>As a start, check out this article on windows user impersonation:</p>
<p><a href="http://www.codeproject.com/KB/system/UserImpersonation.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/system/UserImpersonation.aspx</a></p>
<p>It should give you a place to start. If you need more controll you will need to look into Access Tokens.</p>
|
<p>If you want access to the folders of User A and the folders of User B, then you just need to setup folder permissions in such a way that administrators have permissions to get into all the folders. Normally machine administrators already have those rights. I am assuming here that are talking about normal windows user accounts, and normal machine/domain administrator accounts.</p>
<p>If you want to become User A its means you need User A's active permission to become that person. Impersonation is not simple (from what I have tried), you need to request access through your domain controller and negotiate that you are User B and that you have the rights to impersonate User A, generally that is done by User A and User B sharing and negotiating Credential Handles and Security Contexts. I doubt this is the type of process you're looking to follow.</p>
<p>Some useful functions would include:</p>
<p>To setup the context these are used and data is passed backwards and forwards between User A and User B to negotiate the impersonation</p>
<pre><code>AcquireCredentialsHandle()
InitializeSecurityContext()
AcceptSecurityContext()
CompleteAuthToken()
</code></pre>
<p>Once the negotiations are complete and a security context has been created, these are used to start and stop the impersonation.</p>
<pre><code>ImpersonateSecurityContext()
RevertContext()
</code></pre>
<p>I don't know of any other way to impersonate a user without the active participation of the user in question, or actively logging on as that user.</p>
<p>Hope this helps in some way.</p>
| 26,009
|
<p>I am currently working on automating/improving the release process for packaging my shop's entire product. Currently the product is a combination of: </p>
<ul>
<li>Java server-side codebase </li>
<li>XML configuration and application files</li>
<li>Shell and batch scripts for administrators</li>
<li>Statically served HTML pages </li>
<li>and some other stuff, but that's most of it</li>
</ul>
<p>All or most of which have various versioning information contained in them, used for varying purposes. Part of the release packaging process involves doing a lot of finding, grep'ing and sed'ing (in scripts) to update the information. This glue that packages the product seems to have been cobbled together in an organic, just-in-time manner, and is pretty horrible to maintain. For example, some Java methods create Date objects for the time of release, the arguments for which are updated by a textual replacement, without compiler validation... just, urgh.</p>
<p>I'm trying avoid giving examples of actual software used (i.e. CVS, SVN, ant, etc.) because I'd like to avoid the "use xyz's feature to do this" and concentrate more on general practices. I'd like to blame shoddy design for the problem, but if I had to start again, still using varying technologies, I'd be unsure how best to go about handling this, beyond laying down conventions.</p>
<p>My questions is, are there any best practices or hints and tips for maintaining and updating versioning information across different technologies, filetypes, platforms and version control systems?</p>
|
<p>Indeed, to complete Craig Angus's answer, the rule of thumb here should be to <strong><em>not include any meta-informations in your normal delivery files</em></strong>, but to report those meta-data (version number, release date, and so on) into <em>one</em> special file -- included in the release --.</p>
<p>That helps when you use one VCS (Version Control System) tool from the development to homologation to pre-production.<br>
That means whenever you load a workspace (either for developing, or for testing or for preparing a release into production), it is the versionning tool which gives you all the details.</p>
<p>When you prepare a delivery (a set of packaged files), you should ask that VCS tool about every meta-information you want to keep, and write them in a special file itself included into the said set of files.</p>
<p>That delivery should be packaged in an external directory (outside any workspace) and:</p>
<ul>
<li><p>copied to a shared directory (or a maven repository) if it is a <em>non-official</em> release (but just a quick packaging for helping the team next door who is waiting for your delivery). That way you can make 10 or 20 delivers a day, it does not matter: they are easily disposable.</p></li>
<li><p>imported into the VCS in order to serve as official deliveries, and in order to be deployed easily since all you need is to ask the versionning tool for the right version of the right deliver, and you can begin to deploy it.</p></li>
</ul>
<p>Note: I just described a release management process mostly used for many inter-dependant projects. For one small single project, you can skip the import in the VCS tool and store your deliveries elsewhere.</p>
|
<p>In addition to Craig Angus' ones include the version of tools used.</p>
| 28,003
|
<p>My ClickOnce application uses a third party tool that requires the Visual C++ 2005 redistributable. The third party tool will not work if only the VC++ 2008 redistributable is installed. However, in Visual Studio 2008, the ClickOnce prerequisites do not allow a version to be specified for the VC++ redistributable; it will add a VC++ 2008 prerequisite, which makes sense most of the time. However, in this situation, an earlier version is required. ClickOnce is required, so merge modules are out of the question. Any ideas of how to specify the version?</p>
|
<p>If you can find a machine with VS 2005 installed, the solution shouldn't be too hard. You have the ability to customize what appears in the Prerequisites dialog on the Publish tab of your project.</p>
<ol>
<li>On a machine with VS 2005 installed, go to <strong>\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages</strong> and copy the <strong>vsredist_x86</strong> folder to the machine you are publishing from.</li>
<li>Rename the folder, call it <strong>vsredist<code>_</code>x86<code>_</code>2005</strong> or something similar.</li>
<li>Inside the folder, edit the <strong>\en\package.xml</strong> file. Change the <strong><code><String Name="DisplayName"></code></strong> tag to something that makes sense (<strong>Visual C++ <em>2005</em> Runtime Libraries (x86)</strong>) to differentiate it from the existing 2008 package.</li>
<li>Copy the folder to <strong>C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages</strong>.</li>
<li>Restart Visual Studio if it is open.</li>
</ol>
<p>Now, when you open the Prerequisites dialog you should see a new entry for the 2005 package. I didn't completely test this solution so I may have missed a few details but hopefully this gets you started.</p>
|
<p>I believe you can open the manifest file for your app and modify the versions of the redists your app should be linking against. The listings in the manifest should match what you have in your C:\Windows\WinSxS dirs. There is a <a href="http://www.codeproject.com/KB/cpp/vcredists_x86.aspx" rel="nofollow noreferrer">CodeProject page</a> that gives a good description of using different redistributables.</p>
| 14,895
|
<p>We have two branches:
1. HEAD - the latest version (AKA Trunc)
2. PROD - the released version</p>
<p>When you fix bugs in the released version, which of these do you do:</p>
<ol>
<li>Fix it in PROD, then merge to HEAD</li>
<li>Fix it in HEAD, then merge to PROD</li>
</ol>
<p>The advantage of (1) is that this way you absolutely cannot harm the released version by accidentally bringing over untested code from HEAD (The assumption is that PROD is always more stable/tested than HEAD).</p>
<p>The advantage of (2) is that there might be more usages for a piece of code in HEAD than in PROD, so if you fix only in PROD you might not find all such usages and so slip bugs into HEAD.</p>
<p>I'm personally for (1). What do you think?</p>
|
<p>Bug fixes should be applied to the branch and merged to the the main line of development. You need to do this to avoid bringing new features into a production release that are not intended to be there. Note that easiest way to do this if you need the change in the HEAD may be to apply identical changes in both branches.</p>
|
<p>(1) as well.</p>
<p>Do not forget that <strong>not every bugs fixed into PROD have to be merged back into HEAD</strong>.</p>
<p>Sometimes, your current code has already evolved in such a way the bugs fixed into PROD are no longer relevant.</p>
| 40,441
|
<p>What is the difference between using angle brackets and quotes in an <code>include</code> directive?</p>
<ul>
<li><code>#include <filename></code></li>
<li><code>#include "filename"</code></li>
</ul>
|
<p>What differs is the locations in which the preprocessor searches for the file to be included.</p>
<ul>
<li><p><code>#include <filename></code> The preprocessor searches in an implementation-defined manner, normally in directories pre-designated by the compiler/IDE. This method is normally used to include header files for the C standard library and other header files associated with the target platform.</p>
</li>
<li><p><code>#include "filename"</code> The preprocessor also searches in an implementation-defined manner, but one that is normally used to include programmer-defined header files and typically includes same directory as the file containing the directive (unless an absolute path is given).</p>
</li>
</ul>
<p>For GCC, a more complete description is available in the GCC <a href="https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html" rel="noreferrer">documentation on search paths</a>.</p>
|
<p>There exists two ways to write #include statement.These are:</p>
<pre><code>#include"filename"
#include<filename>
</code></pre>
<p>The meaning of each form is </p>
<pre><code>#include"mylib.h"
</code></pre>
<p>This command would look for the file <code>mylib.h</code> in the current directory as well as the specified list of directories as mentioned n the include search path that might have been set up.</p>
<pre><code>#include<mylib.h>
</code></pre>
<p>This command would look for the file <code>mylib.h</code> in the specified list of directories only.</p>
<p>The include search path is nothing but a list of directories that would be searched for the file being included.Different C compilers let you set the search path in different manners.</p>
| 4,174
|
<p>I'm a PHP developer who is being considered for a job implementing <a href="http://www.brainbankinc.com/idealinkOpen.aspx" rel="nofollow noreferrer">IdeaBank</a>, idea management software written in .net. The software appears to have been selected based on its features and clients. The <a href="http://ideabank.opendns.com/" rel="nofollow noreferrer">OpenDNS community</a> appears to be using it.</p>
<p>Is anyone familiar with this software? What's it like to customize and maintain? Would you recommend it to another programmer?</p>
|
<p>Despite the similar names, the IdeaBank community feature on OpenDNS has nothing to do with the .Net software you cite. It's based on Pligg, which uses PHP.</p>
|
<p>Despite the similar names, the IdeaBank community feature on OpenDNS has nothing to do with the .Net software you cite. It's based on Pligg, which uses PHP.</p>
| 49,758
|
<p>I'm looking for a generic "Row Picker" for JQuery.</p>
<p>We've all seen the cool "Picker" tools like date pickers, color pickers, time pickers, etc, where you click in a text box and a little calendar or color palate or clock or something comes up. You select something (like a date) and the text box is then populated with a value.</p>
<p>I really need an all-purpose "row picker" where you can populate something (a table, divs, etc) with some rows of data (say a list of timezones). This would be linked to a text field and would pop up when the user clicks in the field.</p>
<p>They would click a row (say a timezone), and the timezone id would be passed back to the field.</p>
<p>Anyone know of anything that does this? </p>
<p>Thanks!</p>
|
<p>I don't know about totally generic though you can certainly achieve a row selector fairly easily in jQuery. </p>
<pre><code><script type="text/javascript"> $(function() {
$('table#data_table tr').click(function() {
alert($(this).find('td.id').html());
}); });
</script>
<table border="0" id="data_table">
<tr>
<td class="id">45</td><td>GMT</td>
</tr>
<tr>
<td class="id">47</td><td>CST</td>
</tr>
</table>
</code></pre>
<p>This adds a click to each row, finds the tagged id within the row which would then allow you to do something with it. Obviously you would need to target this to your data table and filter based on the contents. JQuery can then be used to populate the result of the click into the target field. You can then come up with some convention where all your data tables work the same which would allow you to generalise this into a generic picker for your application.</p>
|
<p>I know I'm a year late, and that I'm probably missing something here, but what's wrong with the <code>select</code> element with the <code>size</code> attribute?</p>
<pre><code><select name="test" size="5">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
</code></pre>
<p>This will show all 5 options, and allow the user to select one. It also has absolutely no Javascript dependency if just used in a standard form, but also can handle typical Javascript events well, and also seems to produce the exact appearance that you wanted - not to mention that, as always, you can use CSS to style it as you like.</p>
<p>When standard HTML will work, I say: Use standard HTML.</p>
| 24,344
|
<p>I am going to spend 30 minutes teaching Perl to an experienced programmer. The best way to learn Perl is by writing code. In addition to CPAN, what would you show a programmer so they would understand the expressiveness of Perl, the amount of functionality provided by CPAN, while keeping everything clean and tidy so they walk away comfortable with the language? I'll save the tricky stuff for another day. </p>
<pre>
use warnings;
use strict;
# use A_CPAN_LIB;
sub example_func1 {
# use the CPAN lib or demonstrate some basic feature of Perl
}
example_func1();
# ...
__END__
</pre>
<p><hr>
Here's what I came up with...<br></p>
<h2>Where to Start</h2>
<p>Believe it or not, the man pages. Ok, we'll just use perldoc instead to be Windows friendly.</p>
<p>The perldoc pages (or man pages on Unix/Mac) are excellent for Perl. You can type man perl or perldoc perl</p>
<p><strong>perldoc perl</strong>; # Show an overview and dozens of tutorials; man perl is the same.<br></p>
<p><strong>perldoc perlintro</strong>; # A Perl intro for beginners; man perlintro<br>
<strong>perldoc perlrequick</strong>; # An example Perl regex tutoral<br></p>
<p><strong>perldoc perlfunc</strong>; # Shows builtin Perl functions<br>
<strong>perldoc perlre</strong>; # More Perl regex.<br></p>
<h2>CPAN</h2>
<p>There are thousands of libraries on the Perl library site CPAN.<br>
<strong>perl -MCPAN -e 'install DateTime'</strong><br></p>
<p>perldoc works for installed modules too: perldoc module<br></p>
<p><strong>perldoc DateTime</strong><br>
<strong>perldoc DBI</strong>; # Database API. If this doesn't work then install it:<br>
<strong>perl -MCPAN -e 'install DBI'</strong></p>
<h2>Recommended Modules</h2>
<p><strong>perl -MCPAN -e 'install Moose'</strong>; # Perl does OOP<br>
<strong>perldoc Moose</strong>; # Tell me more about the Moose<br>
<strong>perl -MCPAN -e 'install CGI'</strong>; # Quick and dirty web pages<br>
<strong>perl -MCPAN -e 'install Catalyst'</strong>; # Big web framework. Sometimes have problems installing. Google is your friend<br>
<strong>perl -MCPAN -e 'install CGI::Application'</strong>; # Another web framework<br>
<strong>perldoc CGI::Application</strong>; # Take a quick look at the docs<br>
<br>
A little Q&A.<br>
<br>
Q: Why should I use Perl instead Ruby or Python?<br>
A: More people use Perl. There are more libraries for Perl(way more). Perl is a really great GTD language.<br>
<br>
Q: Why do people hate Perl?<br>
A: You can do some ugly stuff with it. Remember use warnings; use strict; in all of your code. You can check your code before running it. <strong>perl -c</strong> hello.pl<br></p>
<p><br></p>
<h2>Perl Topics</h2>
<h3>Using Perl with Databases</h3>
<p><a href="http://www.perl.com/pub/a/1999/10/DBI.html" rel="nofollow noreferrer"><a href="http://www.perl.com/pub/a/1999/10/DBI.html" rel="nofollow noreferrer">http://www.perl.com/pub/a/1999/10/DBI.html</a></a>
<br></p>
<h3>Using Perl for Web Development</h3>
<p><a href="http://www.catalystframework.org" rel="nofollow noreferrer"><a href="http://www.catalystframework.org" rel="nofollow noreferrer">http://www.catalystframework.org</a></a>
<br></p>
<h3>OO Perl</h3>
<p><a href="http://www.iinteractive.com/moose" rel="nofollow noreferrer"><a href="http://www.iinteractive.com/moose" rel="nofollow noreferrer">http://www.iinteractive.com/moose</a></a>
<br></p>
<h3>Perl 1-Liners</h3>
<p><a href="http://www.perlmonks.org/?node_id=470397" rel="nofollow noreferrer"><a href="http://www.perlmonks.org/?node_id=470397" rel="nofollow noreferrer">http://www.perlmonks.org/?node_id=470397</a></a><br>
<a href="http://sial.org/howto/perl/one-liner" rel="nofollow noreferrer"><a href="http://sial.org/howto/perl/one-liner" rel="nofollow noreferrer">http://sial.org/howto/perl/one-liner</a></a>
<br></p>
<h3>Other Tutorials</h3>
<p><a href="http://perlmonks.org/index.pl?node=Tutorials" rel="nofollow noreferrer"><a href="http://perlmonks.org/index.pl?node=Tutorials" rel="nofollow noreferrer">http://perlmonks.org/index.pl?node=Tutorials</a></a></p>
<h2>Books</h2>
<p>There are dozens.<br>
<a href="http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Dstripbooks&field-keywords=perl&x=0&y=0" rel="nofollow noreferrer">http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Dstripbooks&field-keywords=perl&x=0&y=0</a><br>
<br></p>
<h2>Websites</h2>
<p><a href="http://perlmonks.com" rel="nofollow noreferrer">Perlmonks</a><br>
<a href="http://www.perl.org" rel="nofollow noreferrer">Perl.org</a><br>
<a href="http://pleac.sourceforge.net" rel="nofollow noreferrer">Pleac</a><br>
<a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl">StackOverFlow's Hidden Features of Perl</a><br>
<a href="http://www.cpan.org/misc/cpan-faq.html" rel="nofollow noreferrer">CPAN FAQ</a><br>
<a href="http://www.stonehenge.com/merlyn/LinuxMag" rel="nofollow noreferrer">Randall Schwartz's articles</a><br>
<br>
<br></p>
<h2>Getting Help</h2>
<p><a href="http://www.nabble.com/Perl-f13578.html" rel="nofollow noreferrer">Perl Nabble Forum</a><br>
IRC Channels: freenode, irc.perl.org. There are several:<br>
<br>
irc://irc.perl.org/perl<br>
irc://irc.perl.org/catalyst<br>
irc://irc.freenode.net/modperl<br>
irc://irc.perl.org/perl6<br></p>
|
<p>We wrote a whole book on that called <a href="http://shop.oreilly.com/product/0636920018452.do" rel="nofollow noreferrer">Learning Perl</a>. Check out the table of contents.</p>
<p>This book is a product of teaching people Perl since 1995. It's not geared to any particular application, and shows people the parts of Perl that they'll use for 80% of their Perl programming. We updated it for Perl 5.10, and include sections on using CPAN.</p>
<p>Good luck, :)</p>
|
<p>I agree with some of the other commenters that it truly depends on the type of task that Perl is being used for. Is this person a Windows system admin? Then I'd cover using WMI from Perl (scriptomatic would be a good resource here).</p>
<p>I'd grab a copy of Oreilley's "Perl Cookbook", and find some interesting topics out of there. Here is a link to the book here: <a href="http://books.google.com/books?id=IzdJIax6J5oC&dq=perl+cookbook&pg=PP1&ots=z6ykdpc8fS&source=bn&sig=wEIaAkHmJttmQUVce18SHcXhYLs&hl=en&sa=X&oi=book_result&resnum=6&ct=result" rel="nofollow noreferrer">link text</a></p>
<p>One of my favorite things in Perl is how easy it is to compare lists, looking for unions, intersections, or differences in unique lists (recipe 4.9 in Perl Cookbook). Helps you appreciate the power of Perl.</p>
| 41,372
|
<p>This is my first post here and I wanted to get some input from people doing iPhone development. Other than the Apple DevCenter, where are there good sites to learn iPhone developement?</p>
<p>I know Apple has a tough NDA but there has to be people talking about writing applications for the iPhone.</p>
|
<p><a href="http://www.icodeblog.com/tag/iphone/" rel="nofollow noreferrer">This site</a> covers some of the basics with little regard for the NDA. Start at the bottom and work up.</p>
|
<p>In <a href="http://www.raywenderlich.com/tutorials" rel="nofollow">http://www.raywenderlich.com/tutorials</a> you will find a lots of good tutorials, and you will be up to date with new iOS features as soon as Apple release then.</p>
| 4,165
|
<p>Is it possible to get the progress of an XMLHttpRequest (bytes uploaded, bytes downloaded)? </p>
<p>This would be useful to show a progress bar when the user is uploading a large file. The standard API doesn't seem to support it, but maybe there's some non-standard extension in any of the browsers out there? It seems like a pretty obvious feature to have after all, since the client knows how many bytes were uploaded/downloaded.</p>
<p>note: I'm aware of the "poll the server for progress" alternative (it's what I'm doing right now). the main problem with this (other than the complicated server-side code) is that typically, while uploading a big file, the user's connection is completely hosed, because most ISPs offer poor upstream. So making extra requests is not as responsive as I'd hoped. I was hoping there'd be a way (maybe non-standard) to get this information, which the browser has at all times.</p>
|
<p>For the bytes uploaded it is quite easy. Just monitor the <code>xhr.upload.onprogress</code> event. The browser knows the size of the files it has to upload and the size of the uploaded data, so it can provide the progress info.</p>
<p>For the bytes downloaded (when getting the info with <code>xhr.responseText</code>), it is a little bit more difficult, because the browser doesn't know how many bytes will be sent in the server request. The only thing that the browser knows in this case is the size of the bytes it is receiving. </p>
<p>There is a solution for this, it's sufficient to set a <code>Content-Length</code> header on the server script, in order to get the total size of the bytes the browser is going to receive. </p>
<p>For more go to <a href="https://developer.mozilla.org/en/Using_XMLHttpRequest" rel="noreferrer">https://developer.mozilla.org/en/Using_XMLHttpRequest</a> .</p>
<p>Example:
My server script reads a zip file (it takes 5 seconds):</p>
<pre><code>$filesize=filesize('test.zip');
header("Content-Length: " . $filesize); // set header length
// if the headers is not set then the evt.loaded will be 0
readfile('test.zip');
exit 0;
</code></pre>
<p>Now I can monitor the download process of the server script, because I know it's total length:</p>
<pre><code>function updateProgress(evt)
{
if (evt.lengthComputable)
{ // evt.loaded the bytes the browser received
// evt.total the total bytes set by the header
// jQuery UI progress bar to show the progress on screen
var percentComplete = (evt.loaded / evt.total) * 100;
$('#progressbar').progressbar( "option", "value", percentComplete );
}
}
function sendreq(evt)
{
var req = new XMLHttpRequest();
$('#progressbar').progressbar();
req.onprogress = updateProgress;
req.open('GET', 'test.php', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4)
{
//run any callback here
}
};
req.send();
}
</code></pre>
|
<p>The only way to do that with pure javascript is to implement some kind of polling mechanism.
You will need to send ajax requests at fixed intervals (each 5 seconds for example) to get the number of bytes received by the server.</p>
<p>A more efficient way would be to use flash. The flex component <a href="http://livedocs.adobe.com/flex/3/langref/flash/net/FileReference.html" rel="nofollow noreferrer">FileReference</a> dispatchs periodically a 'progress' event holding the number of bytes already uploaded.
If you need to stick with javascript, bridges are available between actionscript and javascript.
The good news is that this work has been already done for you :)</p>
<p><a href="http://www.swfupload.org" rel="nofollow noreferrer"><strong>swfupload</strong></a></p>
<p>This library allows to register a javascript handler on the flash progress event.</p>
<p>This solution has the hudge advantage of not requiring aditionnal resources on the server side.</p>
| 10,259
|
<p>I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.</p>
<p>if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?</p>
<pre><code>if ( (condition1) | (condition2) ){
// do this
}
</code></pre>
<p>or would I need to nest two if statements to only check the second condition if the first evaluates to false?</p>
<pre><code>if (condition1){
// do this
}else if (condition2){
// do this
}
</code></pre>
<p>I am working in PHP, however, I assume that this may be language-agnostic.</p>
|
<p>For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated.</p>
<p>An old trick for doing obfuscated code was to use this to create if statements, such as:</p>
<pre><code>a || b();
</code></pre>
<p>if "a" is true, "b()" would never be evaluated, so we can rewrite it into:</p>
<pre><code>if(!a)
b();
</code></pre>
<p>and similarly:</p>
<pre><code>a && b();
</code></pre>
<p>would become</p>
<pre><code>if(a)
b();
</code></pre>
<p><strong>Please note</strong> that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised".</p>
<p>EDIT:
As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time.</p>
<p>First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason.</p>
<p>Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless.</p>
|
<p>Since this is tagged language agnostic I'll chime in. For Perl at least, the first option is sufficient, I'm not familiar with PHP. It evaluates left to right and drops out as soon as the condition is met.</p>
| 5,534
|
<p>What are the pros and cons of adopting Open Source software for an organisation? Is there anybody out there who has done this and how well has it been working out with some examples of the softwares they adopted and how it has been in use?</p>
<p>Usually contributions come because people do it as a hobby, then how can we make sure that there will be continued support for it? IMHO, in case of proprietary software there is an incentive for the organisation (money), and they will keep hiring people to keep it under development as long as the software is profitable. Correct me if I am wrong. What are the arguments I might expect from a Manager who might oppose the suggestion to use Open Source softwares?</p>
|
<p>The term "Open Source" only describes a licensing model. Strictly speaking, the only pro that you are guaranteed to have are the freedoms given by the license, and there are no cons that you are guaranteed to have.</p>
<p>There are many Open Source products that are also commercial, created, maintained, and supported by a company for a profit. There are also many Open Source products that are maintained by volunteers but also supported commercially. For example, if you buy Red Hat Enterprise Linux, then Red Hat will support you on all of the products that come with it, even the ones that are maintained by volunteers.</p>
<p>As for how to be sure that there will be continued support, you can't. Not with Open Source, not with proprietary software, not with anything. With Open Source, if the community is large enough, you can be reasonably confident that the community will continue to maintain it (maybe under a new name) even if the current maintainers abandon it, and you have the option of maintaining it yourself or hiring someone else to do it. Maintaining it yourself may not be an attractive option, but it can be a life saver in a pinch.</p>
<p>With proprietary software, if the author decides to stop maintaining it, you are just plain out of luck. Consider, for example, the thousands of users of Visual Basic 6.</p>
|
<p>It doesn't matter what Manager opposing Open Source is saying.</p>
<p>You have to know well Open Source product you are about to use.<br>
You have to be sure that it right solution for company.
You have to be confident that you can find people on market who know or can learn to use that product.
You have to know TCO for that product.</p>
<p>Then you can argue with manager and give him good reasons how company can benefit from Open Source.</p>
<p>Keep in mind that cheapest solution is not best solution. Companies need to earn money not to save money.</p>
| 41,969
|
<p>Is there a way I can configure the MidPointRounding enumeration default setting in a config file (I.e. web.config or app.config) I have a considerable source code base, and I need to configure at the application scope how rounding will occur, whether used in Math.Round or decimal type rounding... I would like to do this in order to get consistent rounding results throughout the application without changing every line that works with a decimal type or uses Math.Round....</p>
|
<p>You can play games with post-compile tools that alter the assembly to call your function instead of Math.Round. However, I would just bite the bullet and change the source code.</p>
|
<p>Enum.Parse() is your friend here</p>
<pre><code>MyEnum GetEnumValue(string enumString) {
return (MyEnum)Enum.Parse(typeof(MyEnum),enumString);
}
</code></pre>
<p>Obviously you'd also need some error-checking on the string you're getting from you're config file in which case you might want to return a default.</p>
| 8,911
|
<p>I'm running JBoss 4.0.5 on Windows 2003 x64 and wonder if there is any way to get a dump of all threads? </p>
<ul>
<li><p>It's stared with FireDaemon so I don't have a console windows in which to ctrl-break.</p></li>
<li><p>It's running under java 1.5 so jstack won't work.</p></li>
<li><p>I tried some program someone had made called sendsignal.exe, which I think actually crashed JBoss (not certain, but not going to try it again), if this was because JBoss runs under win x64 or because it runs as LocalSystem and I only have access to an "ordinary" user I don't know. It actually worked on my laptop, but it's 32-bit and I'm running as the same user as JBoss there.</p></li>
</ul>
<p>Someone has any other ideas that might work?</p>
|
<p>I actually found a better way than what <a href="https://stackoverflow.com/users/3253/gowri">Gowri</a>
suggested (after starting to implementing the jsp).</p>
<p>There is actually a way to dump the threads from the jmx-console in the Server Info MBean, see <a href="http://www.jboss.org/community/docs/DOC-9804" rel="nofollow noreferrer">Generate a thread dump with the JMX Console</a></p>
|
<p>You could just write a jsp that does <code>Thread.getAllStackTraces()</code> and print out the stacktracelements in an amenable format. Then hitting the URL of that jsp at any time would give you the stack dump of all threads at that time.</p>
| 39,754
|
<p>According <a href="http://msdn.microsoft.com/en-us/library/y3bwdsh3.aspx" rel="noreferrer">this MSDN article</a> <em>HttpApplication</em>.EndRequest can be used to close or dispose of resources. However this event is not fired/called in my application.</p>
<p>We are attaching the handler in Page_Load the following way:</p>
<pre><code>HttpContext.Current.ApplicationInstance.EndRequest += ApplicationInstance_EndRequest;
</code></pre>
<p>The only way is to use the Application_EndRequest handler in Global.asax, but this is not acceptable for us. </p>
|
<p>You can use your own HttpModule to capture the EndRequest if you don't want to use the global.asax.</p>
<pre><code>public class CustomModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.EndRequest += new EventHandler(context_EndRequest);
}
private void context_EndRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
// use your contect here
}
}
</code></pre>
<p>You need to add the module to your web.config</p>
<pre><code><httpModules>
<add name="CustomModule" type="CustomModule"/>
</httpModules>
</code></pre>
|
<p>The page is probably being disposed before the event fires. You might want to try to do your work in the Page_Unload handler.</p>
| 29,683
|
<p>I'm kind of curious how I should approach a problem with iPhones and communication between two phones.</p>
<p>I have an idea for an application that needs to send data between two known phones. The problem is that the data could be very small or very large. I want to have intermediate storage on a server and a messaging layer, but I want there to be performant means to communicate between devices for shorter, unimportant messages.</p>
<p>You always hear about networking and client to client communication with popular platforms and protocols, but I'm curious what people's thoughts are on doing p2p style communication with an iPhone.</p>
<p>I'm pretty sure it should (and can) be treated as just a simple addressable machine... so I would have to build NAT traversing network code into the iPhone itself. A thought I had would be some sort of UPnP situation where I would ask to NAT a particular port for communication to the devices... but I guess I could just as easily turn it into a polling situation. </p>
<p>Granted, I understand that Apple will have a "push" mechanism for developers eventually but I want to get the app out the door before hand...</p>
<p>Just curious about thoughts on this type of thing... any thoughts on multi-player game situations would also directly apply to (and benefit from) this question.</p>
|
<p>Have you given the WiTap sample from Apple a try? It addresses the issue of discoverability (via Bonjour) and connectivity (via basic TCP). It may not be as robust as what you are looking for, but it's worth a look:</p>
<p><a href="http://developer.apple.com/iphone/library/samplecode/WiTap/index.html" rel="nofollow noreferrer">http://developer.apple.com/iphone/library/samplecode/WiTap/index.html</a></p>
|
<p>Look at the docs for Game Kit in the iPhone 3.0 SDK. It allows iPhones to connect to one another locally with Bluetooth, or via wi-fi/3G. It addresses both peer-to-peer and client-server architectures. It provides unreliable and reliable links.</p>
| 23,607
|
<p>I'd like to do something like this</p>
<blockquote>
<pre><code>raiserror(concat('Error in case @isFishy =', @isFishy, ' @isSmarmy=', @isSmarmy, ' @isTasty = ', @isTasty), 10, 1)
--or
raiserror('Error in case @isFishy =' + @isFishy + ' @isSmarmy=' + @isSmarmy + ' @isTasty = ' + @isTasty, 10, 1)
</code></pre>
</blockquote>
<p>But it just isn't working. How do I accomplish this? I'm in SQL Server 2005.</p>
|
<p>The error message in RAISERROR has actually similar syntax to printf function in C, so assuming your arguments are of the type of integer you would need to use:</p>
<pre><code>raiserror(N'Error in case @isFishy = %d @isSmarmy = %d @isTasty = %d',10,1,@isFishy,@isSmarmy,@isTasty)
</code></pre>
<p>check out <a href="http://msdn.microsoft.com/en-us/library/ms178592(SQL.90).aspx" rel="noreferrer">BOL</a> for details and other options</p>
|
<p>I use raiserror a lot. We have some stored procedures that are called from a .Net app each night for batch processing, and the .Net app wants to log the procedure output this way. I don't know why, but I generally have to build the string before calling raiserror. </p>
| 27,964
|
<p>I'm trying to write a regex that will parse out the <strong>directory and filename</strong> of a fully qualified path using matching groups.</p>
<p>so...</p>
<pre><code>/var/log/xyz/10032008.log
</code></pre>
<p>would recognize <code>group 1 to be "/var/log/xyz"</code> and <code>group 2 to be "10032008.log"</code></p>
<p>Seems simple but I can't get the matching groups to work for the life of me.</p>
<p>NOTE: As pointed out by some of the respondents this is probably not a good use of regular expressions. Generally I'd prefer to use the file API of the language I was using. What I'm actually trying to do is a little more complicated than this but would have been much more difficult to explain, so I chose a domain that everyone would be familiar with in order to most succinctly describe the root problem.</p>
|
<p>Try this:</p>
<pre><code>^(.+)\/([^\/]+)$
</code></pre>
<p>EDIT: escaped the forward slash to prevent problems when copy/pasting the Regex</p>
|
<p>Try this:</p>
<pre><code>/^(\/([^/]+\/)*)(.*)$/
</code></pre>
<p>It will leave the trailing slash on the path, though.</p>
| 20,399
|
<p>Java 1.5, Linux</p>
<p>I do have a screen which contains different textareas and textfields.
I do have acess to the application frame, but not to the components inside the frame, because i only get an implementation of an interface.</p>
<p>When i try to add german umlauts i see a rectangle in the text component, because the character is not supported.
Which font or which system-propertiy i have to set to support "umlauts" under linux.
On windows the characters are shown correctly.</p>
|
<p>It sounds like a character encoding problem or font problem... Like using "windows" encoding in a Linux environment. You should check the following:</p>
<ul>
<li>Can you write those characters in a normal texteditor in your linux distro? </li>
<li>Are those characters from input files in your java application or is it from the source, if so what OS did you use to write the source? </li>
<li>If they are from a source file or resource file, have you checked that the characters is actually readable in the sourcefile in Linux? </li>
<li>If you open the sourcefile in for instance vim, what encoding does it use? (It usually says in the lower part of the screen just after you opened the file)</li>
</ul>
<p>If you tell what happens when you do this, we may have a better idea of what is wrong. :)</p>
<p><strong>UPDATE:</strong>
The reason I wanted you to check this is that I know the so called "windows encoding" can create problems in other OS'es. You say you can write umlauts on the console but not in vi, what do you get instead, squares? </p>
<p>It does't matter that users isn't supposes to view the ini file, if you created the ini files manually in Linux I suppose you were able to write umlauts then. You should find out what character encoding these files and the TCP connection uses. It should be UTF-8, "Western" or "Windows" or "Latin-1" etc. may cause problems.</p>
<p>If everything is UTF-8, readable everywhere except in your application I would start to suspect a missing font issue. </p>
|
<p>The square box is the unicode symbol for when the character in question can't be displayed as the font doesn't contain it.</p>
<p>You'll either need to switch the text boxes to a font that does contain the German characters, or find some other way of doing the substitution for just that character (which may not be possible within Java).</p>
| 42,180
|
<p>I was working with a new C++ developer a while back when he asked the question: "Why can't variable names start with numbers?"</p>
<p>I couldn't come up with an answer except that some numbers can have text in them (123456L, 123456U) and that wouldn't be possible if the compilers were thinking everything with some amount of alpha characters was a variable name.</p>
<p>Was that the right answer? Are there any more reasons?</p>
<pre><code>string 2BeOrNot2Be = "that is the question"; // Why won't this compile?
</code></pre>
|
<p>Because then a string of digits would be a valid identifier as well as a valid number.</p>
<pre><code>int 17 = 497;
int 42 = 6 * 9;
String 1111 = "Totally text";
</code></pre>
|
<p>I think the simple answer is that it can, the restriction is language based. In C++ and many others it can't because the language doesn't support it. It's not built into the rules to allow that. </p>
<p>The question is akin to asking why can't the King move four spaces at a time in Chess? It's because in Chess that is an illegal move. Can it in another game sure. It just depends on the rules being played by. </p>
| 44,479
|
<p>How do I capture the output of "%windir%/system32/pnputil.exe -e"?
(assume windows vista 32-bit)</p>
<p>Bonus for technical explanation of why the app normally writes output to the cmd shell, but when stdout and/or stderr are redirected then the app writes nothing to the console or to stdout/stderr?</p>
<pre>
C:\Windows\System32>PnPutil.exe --help
Microsoft PnP Utility {...}
C:\Windows\System32>pnputil -e > c:\foo.txt
C:\Windows\System32>type c:\foo.txt
C:\Windows\System32>dir c:\foo.txt
Volume in drive C has no label.
Volume Serial Number is XXXX-XXXX
Directory of c:\
09/10/2008 12:10 PM 0 foo.txt
1 File(s) 0 bytes
</pre>
|
<p>Doesn't seem like there is an easy way at all. You would have to start hooking the call to WriteConsole and dumping the string buffers. See <a href="http://objectmix.com/tcl/366746-autoexpect-under-windows-later-mac-linux.html#post1359780" rel="nofollow noreferrer">this post</a> for a similar discussion.</p>
<p>Of course, if this is a one off for interactive use then just select all the output from the command window and copy it to the clipboard. (Make sure you cmd window buffer is big enough to store all the output).</p>
|
<p>Some applications are written so that it works in piping scenarios well e.g.</p>
<pre><code>svn status | find "? "
</code></pre>
<p>is a command that pipes output of <code>svn status</code> into <code>find "? "</code> so it would filter subversion output down to unknown files (marked with a question mark) in my repos.</p>
<p>Imagine if svn status would also output a header that says "Copyright ? 2009" That very specific header line would also show up. Which is <em>not</em> what I expect.</p>
<p>So certain tools, like those of Sysinternals' will write any header information <em>only</em> if it is printed directly to the command window, if any kind of redirection is detected, then those header information will not be written as by the reason above.</p>
<p>Header information becomes noise when used in piping/automation scenarios.</p>
<p>I suppose if you can't use <code>></code> to output to a file, its because the tool is hardwired not to do so. You'll need an indirect means to capture it.</p>
<p>Hope this helps.</p>
| 7,819
|
<p>Are <a href="http://jquery.com/demo/thickbox/" rel="noreferrer">modal windows/dialogs</a> considered a good practice for websites? One of the things that concerns me about using a modal window is that it is so much like a pop-up window and it could cause user frustration or cause users to simply close it because it's intrusive. Do you know of any studies that talk about user preferences and use rates? </p>
<p>Are there any accessibility issues beyond having the a modal window link load the content in a new page when JavaScript is turned off? Do you <em>like</em> sites or web apps that use modal windows? Why or why not? What are good and bad practices for implementing modal windows? I know modals are probably most often used when displaying pictures or galleries, but what are some other practical use cases? Do you use them on your site and what lead you to your decision? </p>
|
<p>From a practice standpoint - excluding accessibility - modal windows provide an alternative that are less startling as, say, dialog boxes and feel less intrusive than pop-up windows. They usually have a more cohesive feel to the site than either of the two aforementioned method. Aside from pictures or media, I've used modal dialogs to serve the same purpose as dialog boxes - to get the user to give some form of required input, or to acknowledge something before letting them interact with the site again.</p>
<p>From a purely accessible standpoint, they aren't so great. They typically require JavaScript, and, because of the way that modals are managed with respect to the DOM, screen readers will not interpret them well. To combat this, it's always a good idea to degrade gracefully - one suggestion is to take the content of the modal dialog and place it on a page. Whenever the modal dialog <em>should</em> appear, have the current page redirect to the 'modal page', get the user's input, and return to the page it was on.</p>
<p>Finally, as far as my personal opinions are concerned, I don't mind modal windows. I think that, when used correctly, they provide a decent experience - if something <strong>has</strong> to get my attention, then I'd rather it do so without redirecting me from the page, showing an ugly operating system themed dialog, or a pop-up (which my browser will likely block, anyway). I guess, to sum it up, if I had to choose <em>how</em> I'd like to be interrupted, then I'd choose a modal dialog.</p>
|
<p>37Signals has an interesting post on modals <a href="http://www.37signals.com/svn/posts/1149-modal-overlays-beyond-the-dialog-box" rel="nofollow noreferrer">here</a>. They talk about using modals to indicate importance through screen size, where the modal overlay isn't important enough to necessitate navigating to a new page.</p>
| 25,251
|
<p>I am currently creating a custom control that needs to handle animation in a C# project. It is basically a listbox that contains a fixed number of elements that are subject to move. An element (another user control with a background image and a couple of generated labels) can move upwards, downwards or be taken out of the list. </p>
<p>I would like to create animated movement as the elements get moved around within the container custom control but it seems to me that moving controls around using lines such as</p>
<pre><code>myCustomControl.left -= m_iSpeed;</code></pre>
<p>triggered within a timer event is flickery and has a terrible rendering, even with double buffering turned on.</p>
<p>So here's the question : <strong>What is the best way to achieve a flicker-free animated C# control?</strong> Should I just not create custom controls and handle all of the drawing within a panel's background image that I generate? Is there a super animation method that I have not discovered? :)</p>
<p>Thanks!</p>
|
<p>your best bet for flicker-free animation is to do the painting yourself (use the Graphics object in the Paint event handler) and use double-buffering. In your custom control you will need code like this in the constructor:</p>
<pre><code>this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor,
true);
</code></pre>
|
<p>The normal way to get flicker-free animation is to implement double-buffering. Take a look at this Code Project article</p>
<p><a href="http://www.codeproject.com/KB/GDI-plus/flickerFreeDrawing.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/GDI-plus/flickerFreeDrawing.aspx</a></p>
<p>Minimizing calls to paint until you are ready is also a good idea.</p>
| 22,040
|
<p>Is there a free software for creating windows help files for your program?</p>
<p>I would like something that allows an output of both CHM and HTML files.</p>
|
<p>Yes. HelpMaker from <a href="http://sourceforge.net/projects/helpmaker/" rel="nofollow noreferrer">sourceforge</a> (The original site <a href="http://www.vizacc.com" rel="nofollow noreferrer">www.vizacc.com</a> is down). Best free help utility ever.</p>
|
<p>It's not "free" but the best software I've ever come across is HelpScribble from Just Great Software. I use it on Windows 7 without any problem. What I like most is its ability to integrate SHG files into the helpfile. A picture is worth a thousand words so I tend to use screen images where I capture buttons, text boxes or whatever. The user can see that screen and then just click of the display they want more information on an "BOOM!" ... the explanation pops right up! There's no need to thumb through pages of a manual or screens.</p>
| 17,512
|
<p>I wrote a simple batch file as a PowerShell script, and I am getting errors when they run.</p>
<p>It's in a scripts directory in my path. This is the error I get:</p>
<blockquote>
<p>Cannot be loaded because the execution of scripts is disabled on this system.
Please see "get-help about-signing".</p>
</blockquote>
<p>I looked in the help, but it's less than helpful.</p>
|
<p>It could be PowerShell's default security level, which (IIRC) will only run signed scripts.</p>
<p>Try typing this:</p>
<pre class="lang-none prettyprint-override"><code>set-executionpolicy remotesigned
</code></pre>
<p>That will tell PowerShell to allow local (that is, on a local drive) unsigned scripts to run.</p>
<p>Then try executing your script again.</p>
|
<p>On Windows 10:
Click change security property of myfile.ps1 and change "allow access" by right click / properties on myfile.ps1</p>
| 3,184
|
<p>I would like to use Haskell more for my projects, and I think if I can get started using it for web apps, it would really help that cause. I have tried happs once or twice but had trouble getting off the ground. Are there simpler/more conventional (more like lamp) frameworks out there that I can use or should I just give happs another try?</p>
|
<p>The best tools as of 2011 are:</p>
<ul>
<li><a href="http://snapframework.com/" rel="nofollow noreferrer">Snap</a></li>
<li><a href="http://www.yesodweb.com/" rel="nofollow noreferrer">Yesod</a>; or</li>
<li><a href="http://happstack.com/" rel="nofollow noreferrer">Happstack</a></li>
</ul>
<p>The web development community around Haskell has been thriving on the competition between these communities.</p>
<p>The authors even compare their frameworks here: <a href="https://stackoverflow.com/questions/5645168/comparing-haskells-snap-and-yesod-web-frameworks">Comparing Haskell's Snap and Yesod web frameworks</a></p>
|
<p>There is also <a href="http://hope.bringert.net/about" rel="nofollow noreferrer">Hope</a> (link is depreciated), although it doesn't seem to have gained as much traction as <a href="http://happs.org/" rel="nofollow noreferrer">HApps</a> and <a href="http://www2.informatik.uni-freiburg.de/~thiemann/WASH/" rel="nofollow noreferrer">WASH</a>. However, the site has also been quiet for about a year.</p>
| 7,388
|
<p>I have a string that looks like this:</p>
<pre><code>"Name1=Value1;Name2=Value2;Name3=Value3"
</code></pre>
<p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p>
<pre><code>dict = {
"Name1": "Value1",
"Name2": "Value2",
"Name3": "Value3"
}
</code></pre>
<p>I have looked through the modules available but can't seem to find anything that matches.</p>
<hr>
<p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p>
<p>I'll do it myself then.</p>
|
<p>There's no builtin, but you can accomplish this fairly simply with a generator comprehension:</p>
<pre><code>s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))
</code></pre>
<p><strong>[Edit]</strong> From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):</p>
<pre><code>>>> s = "Name1='Value=2';Name2=Value2;Name3=Value3"
>>> dict(csv.reader([item], delimiter='=', quotechar="'").next()
for item in csv.reader([s], delimiter=';', quotechar="'").next())
{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}
</code></pre>
<p>Depending on the exact structure of your format, you may need to write your own simple parser however.</p>
|
<pre><code>easytiger $ cat test.out test.py | sed 's/^/ /'
p_easytiger_quoting:1.84563302994
{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1'}
p_brian:2.30507516861
{'Name2': 'Value2', 'Name3': "'Value3'", 'Name1': 'Value1'}
p_kyle:7.22536420822
{'Name2': ['Value2'], 'Name3': ["'Value3'"], 'Name1': ['Value1']}
import timeit
import urlparse
s = "Name1=Value1;Name2=Value2;Name3='Value3'"
def p_easytiger_quoting(s):
d = {}
s = s.replace("'", "")
for x in s.split(';'):
k, v = x.split('=')
d[k] = v
return d
def p_brian(s):
return dict(item.split("=") for item in s.split(";"))
def p_kyle(s):
return urlparse.parse_qs(s)
print "p_easytiger_quoting:" + str(timeit.timeit(lambda: p_easytiger_quoting(s)))
print p_easytiger_quoting(s)
print "p_brian:" + str(timeit.timeit(lambda: p_brian(s)))
print p_brian(s)
print "p_kyle:" + str(timeit.timeit(lambda: p_kyle(s)))
print p_kyle(s)
</code></pre>
| 22,617
|
<p>Is there a way I can access (for printout) a list of sub + module to arbitrary depth of sub-calls preceding a current position in a Perl script?</p>
<p>I need to make changes to some Perl modules (.pm's). The workflow is initiated from a web-page thru a cgi-script, passing input through several modules/objects ending in the module where I need to use the data. Somewhere along the line the data got changed and I need to find out where.</p>
|
<p>You can use <a href="http://search.cpan.org/dist/Devel-StackTrace/" rel="noreferrer">Devel::StackTrace</a>.</p>
<pre><code>use Devel::StackTrace;
my $trace = Devel::StackTrace->new;
print $trace->as_string; # like carp
</code></pre>
<p>It behaves like Carp's trace, but you can get more control over the frames.</p>
<p>The one problem is that references are stringified and if a referenced value changes, you won't see it. However, you could whip up some stuff with <a href="http://search.cpan.org/dist/PadWalker/" rel="noreferrer">PadWalker</a> to print out the full data (it would be huge, though).</p>
|
<p>One that is more pretty: <a href="https://metacpan.org/pod/Devel::PrettyTrace" rel="nofollow" title="Devel::PrettyTrace">Devel::PrettyTrace</a></p>
<pre><code>use Devel::PrettyTrace;
bt;
</code></pre>
| 28,344
|
<p>Let's say at your job your boss says,</p>
<blockquote>
<p>That system over there, which has lost all institutional knowledge but seems to run pretty good right now, could we dump double the data in it and survive?</p>
</blockquote>
<p>You're completely unfamiliar with the system.</p>
<p>It's in SQL Server 2000 (primarily a database app).</p>
<p>There's no test environment.</p>
<p>You might be able to hijack it on the weekends if you needed to run a benchmark.</p>
<p>What would be the 3 things you'd do to convince yourself and then your manager that you could take on that extra load. And if you couldn't do it, on the same hardware... the extra hardware (measured in dollars) it would take to satisfy that request.</p>
<p>To address the response from doofledorfer, you assumptions are almost all 180 degrees off. But that's my fault for an ambiguous question.</p>
<ol>
<li><p>One of the main servers runs 7x24 at 70% base and spikes from there and no one knows what it is doing.</p></li>
<li><p>This isn't an issue of buy-in or whining... Our company may not have much of a choice in the matter.</p></li>
<li><p>Because this is being externally mandated, delays in implementation could result in huge fines. So large meeting to assess risk are almost impossible. There is one risk, that dumping double the data would take the system down for the existing customers.</p></li>
</ol>
<p>I was hoping someone would say something like, see if you take the system off line Sunday night at midnight and run SQLIO tests to see how close the storage subsystem is to saturation. Things like that.</p>
|
<ol>
<li><p>Set up a test environment, even if I have to do it on my laptop.</p></li>
<li><p>Enable some kind of logging on the production system to get an idea of the volume of transactions in addition to the volume of data.</p></li>
<li><p>Read the source code as I run stress tests on my laptop with increasing amounts of data.</p></li>
</ol>
<p>Having said that, I sympathize with this assignment, because it's unfair. It's like asking someone in a boat if the boat can float with twice the cargo -- but you can't get out of the boat or take it out of its regular service.</p>
|
<p>it mostly depends on its current level. If doubling is going from 2GB to 4GB just do it. If it's going from 1TB to 2TB you've got some planning to do.</p>
<p>I'd collect some info using Performance Monitor and provide it to help make an educated decision.</p>
| 38,347
|
<p>After some find and replace refactoring I ended up with this gem:</p>
<pre><code>const class A
{
};
</code></pre>
<p>What does "const class" mean? It seems to compile ok.</p>
|
<blockquote>
<p>What does "const class" mean? It seems to compile ok.</p>
</blockquote>
<p>Not for me it doesn't. I think your compiler's just being polite and ignoring it.</p>
<p><strong>Edit:</strong> Yep, VC++ silently ignores the const, GCC complains.</p>
|
<p>Try compiling it with GCC, it will give you below error:<br>
<code>error: qualifiers can only be specified for objects and functions.</code></p>
<p>As you can see from the error that only objects(variables, pointers, class objects etc.) and functions can be constant. So try making the object as constant, then it should compile fine.<br>
<code>const class A {};</code><br>
<code>const A a ;</code></p>
| 25,367
|
<p>Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way.</p>
<p>Consider the following situation :</p>
<pre><code>var query =
from c in db.Customers
where (c.ContactFirstName.Contains("BlackListed") ||
c.ContactLastName.Contains("BlackListed") ||
c.Address.Contains("BlackListed"))
select c;
</code></pre>
<p>The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause?</p>
<p>An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.</p>
|
<p>@Geoff has the best option, justing Dynamic LINQ.</p>
<p>If you want to go the way of building queries at runtime using Lambda though I'd recomment that you use the PredicateBuilder (<a href="http://www.albahari.com/nutshell/predicatebuilder.aspx" rel="noreferrer">http://www.albahari.com/nutshell/predicatebuilder.aspx</a>) and have something such as this:</p>
<pre><code>Expression<Fun<T,bool>> pred = null; //delcare the predicate to start with. Note - I don't know your type so I just used T
if(blacklistFirstName){
pred = p => p.ContactFirstName.Contains("Blacklisted");
}
if(blacklistLastName){
if(pred == null){
pred = p => p.ContactLastName.Contains("Blacklisted"); //if it doesn't exist just assign it
}else{
pred = pred.And(p => p.ContactLastName.Contains("Blacklisted"); //otherwise we add it as an And clause
}
}
</code></pre>
<p>And so on for all the columns you want to include. When you get to your query you just need something like this:</p>
<pre><code>var results = db.Customers.Where(pred).Select(c => c);
</code></pre>
<p>I've used this to do building of LINQ for searching where there are about 20 different options and it produces really good SQL.</p>
|
<p>Since this is not LINQ to Objects, but rather LINQ to SQL, you have no other alternative beside using either Expressions or a stored procedure.</p>
| 29,018
|
<p><code>mime_content_type()</code> is deprecated.</p>
<p>How can I find the <code>MIME type</code> of a local file using <code>PHP5</code> but without using this deprecated method or the <code>PECL fileinfo</code> extension?</p>
<p>Edit: That's what I was afraid of. It's unfortunate that they deprecated a built-in function in favour of one that requires an extension that isn't always available.</p>
|
<p>If you can't use the fileinfo extension, and you don't want to use mime_content_type, your options are limited.</p>
<p>Most likely you'll need to do a lookup based on the file extension. mime_content_type did something a bit more intelligent and actually looked for special data in the file to determine the mime type.</p>
|
<p>The <a href="http://getid3.sourceforge.met" rel="nofollow noreferrer" title="getId3">getID3()</a> library is a quick and easy works-most-of-the-time option. Originally named for a project to obtain MP3 ID3 data, the library does two hecks of a lot more than that and is quite convenient for all sorts of common or odd file meta data tasks.</p>
<p>I've used it to get the MIME types of files for online image and video tools. In all the testing I've done I've not seen getID3 get the MIME type wrong.</p>
<p>I've also used it to check if QuickTime videos have streaming hints. I mention this as an example of versatility.</p>
<p>A second more time consuming option is to roll your own MIME type checker as already suggested. If you have a MIME magic file you can go a little further than a lookup on the file extension by comparing the first n bytes of file data against a first-n-bytes to MIME type lookup table derived from your MIME magic file.</p>
<p>A typical MIME magic file will contain in excess of 500 sets of MIME types which might result in slow comparisons (lots of checks to make). Hard-coding the 10 most common MIME type checks in your home rolled solution will help there.</p>
| 7,401
|
<p>In the spirit of <a href="https://stackoverflow.com/questions/171156/best-practices-always-return-a-never-a">Best Practices: Always return a ____, never a ____</a>, I face a similar question in my upcoming <a href="https://stackoverflow.com/questions/219164/generics-in-legacy-code">migration from JDK1.4.2 to JDK5 and more</a>. (Yes, I <em>know</em>, <a href="http://java.sun.com/products/archive/eol.policy.html" rel="noreferrer">JDK1.4.2 is EOL!</a> ;-) ).</p>
<p>For functions returning a collection (which are not simple <a href="https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property">property collections</a>), I always prefer (in JDK1.4.2) returning an Array instead of a generic List, because:</p>
<ul>
<li>it enforces the returning type (<code>MyObject[]</code> instead of List of Objects, much more <strong><em>type-safe</em></strong> on a static -- as in 'compilation' -- level)</li>
<li>it <em>suggests</em> a 'read-only' character to the returned collection (it is more complicated to add an element to the collection, even though this is not as rigorous as the 'read-only' keyword in c#). This is not the same as saying it is 'immutable' since the references inside the array can still be modified...</li>
</ul>
<p>Of course, I do always <em>create</em> this returned array (I do not expose any 'internal' array)</p>
<p>Now, In JDK5 and more, I could use <code>List<MyObject></code> if I want to. </p>
<p><strong>What are the good reasons for choosing to return <code>MyObject[]</code> instead of List or <code>Collection<MyObject></code> when coding in java5 ?</strong></p>
<p>Bonus, if <code>Collection<MyObject></code> is used, is it possible to:</p>
<ul>
<li>enforce a read-only attribute on the returned collection ? (no <code>add()</code> or <code>remove()</code> possible)</li>
<li>enforce an immutable aspect to the returned collection ? (even the references of that collection can not be modified)</li>
</ul>
<p>PS: The <a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html" rel="noreferrer">JavaGenericFAQ</a> did not quite have that one.</p>
|
<p>Prefer Collection (or List, or Set as appropriate) to an array. With generics you get the type-checking that was lacking pre-Java 5. Also, by exposing only the interface, you are free to change the implementation later (e.g. switch an ArrayList for a LinkedList).</p>
<p>Arrays and generics don't mix very well. So, if you want to take advantage of generics, you should <em>usually</em> avoid arrays.<br>
I.e: You can't generically create an array. For example, if T is a generic type then "new T[0]" doesn't compile. You'd have to do something like "(T[]) new Object[0]", which generates an unchecked cast warning. For the same reason, you can't use generic types with varargs without warnings.</p>
<p>Using <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#unmodifiableCollection(java.util.Collection)" rel="noreferrer">Collections.unmodifiableCollection</a> (and similar methods), you get the read-only constraint (which you can't achieve with an array - you would have to return a clone of the array).</p>
<p>You can't enforce immutability of members, but then you can't do that with an array either.</p>
|
<p>Check out the unmodifiable* methods in <code>Collections</code> class to make returned collections read-only/immutable. This will wrap the original collection in a list that prevents access to changing the list itself (the elements themselves are not immutable though).</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#unmodifiableList(java.util.List)" rel="nofollow noreferrer">unmodifiableList</a> for instance.</p>
<p>For me it depends on how the returned list will be used. What other methods is it being passed to, and how will it be used? In general I'd prefer the generic collection over an array, but would change it on a case by case basis.</p>
<p>The array will probably perform faster as well if you're doing something critical.</p>
| 27,882
|
<p>Does anyone know of a good tool for debugging JSPs from within Eclipse? I'd like to be able to set and watch breakpoints, step through the Java code/tags, etc within Eclipse while the app is running (under JBoss in my case).</p>
<p>Presumably, it's reasonably straightforward to debug the servlet class that's generated from a JSP, but it's also fairly unappealing.</p>
|
<p>If you have <a href="https://en.wikipedia.org/wiki/Eclipse_(software)#Web_Tools_Platform" rel="nofollow noreferrer">WTP</a> installed, you can set breakpoints within a JSP and they work fine in a regular "remote debug" session. However, once you've stopped on a breakpoint, stepping through the code is nigh on impossible and finding whatever it is that you wish to inspect takes a lot of digging around in the "Variables" view.</p>
|
<p>Apparently, Eclipse has <a href="http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.wst.server.ui.doc.user%2Ftopics%2Ftdbgjsp.html" rel="nofollow">a troubleshooting page</a> on this, though when I tried it I did get a 404 with it. Hopefully this can at least get you started in a good direction.</p>
| 15,019
|
<p>Within SQL Server Integration Services (SSIS) there is the ability to setup a connection to a flat file that can hold millions of records and have that data pushed to a SQL DB. Furthermore, this process can be called from a C# app by referencing and using the Microsoft.SqlServer.Dts.Runtime namespace. </p>
<p>Would a flat file with millions of records best be ran with SSIS, or would the collective "you" prefer a c# app with multiple worker threads(one to read and add the row to variable, one to write from that variable to the DB), and a "mother" class that manages those threads? (the dev box has two cpu's)</p>
<p>I have seen this data (<a href="http://weblogs.sqlteam.com/mladenp/articles/10631.aspx" rel="nofollow noreferrer">sql team blog</a>) stating that for a flat file with a million lines, SSIS is the fastest:</p>
<pre><code>Process Duration (ms)
-------------------- -------------
SSIS - FastParse ON 7322 ms
SSIS - FastParse OFF 8387 ms
Bulk Insert 10534 ms
OpenRowset 10687 ms
BCP 14922 ms
</code></pre>
<p>What are your thoughts?</p>
|
<p>I can only speak for myself and my experience. I would go with SSIS, since this is one of those cases where you might be re-inventing the wheel unnecessarily. This is a repetitive task that has already been solved by SSIS.</p>
<p>I have about 57 jobs (combination of DTS and SSIS) that I manage on a daily basis. Four of those routinely handle exporting between 5 to 100 million records. The database I manage has about 2 billion rows. I made use of a script task to append the date, down to the millisecond, so that I can run jobs several times a day. Been doing that for about 22 months now. It's been great!</p>
<p>SSIS jobs can also be scheduled. So you can set it and forget it. I do monitor everything every day, but the file handling part has never broken down.</p>
<p>The only time I had to resort to a custom C# program, was when I needed to split the very large files into smaller chunks. SSIS is dog slow for that sort of stuff. A one gig text file took about one hour to split, using the script task. The C# custom program handled that in 12 minutes.</p>
<p>In the end, just use what you feel comfortable using.</p>
|
<p>SSIS is incredibly fast. In addition, if it's something that needs to occur repeatedly, you can setup an agent to fire it off on schedule. Writing it yourself is one thing, trying to make it multithreaded gets a lot more complicated than it appears at first.</p>
<p>I'd recommend SSIS 9 times out of ten.</p>
| 17,662
|
<p>I need lucene to search for synonyms as well as the actual keyword. that is if I search for "CI", I want it to search for CI OR "continues integration". at the moment I search for keywords I have the synonyms for and replace them with the "OR-ed" version, but I suspect there should be a better way to do this. my method will not work for complex queries where you have something like "x AND y OR NOT z".</p>
|
<p>That's pretty much how I was planning on implementing this functionality. I was planning on building my own version of this but then I ran across this site <a href="https://www.ebswift.com/wordnetnet.html" rel="nofollow noreferrer">WordNet.Net</a> which seems to try to address the issue of building the synonyms. There is a wordnet extension to Lucene.Net which rewrites the query, so I'm guessing that is really the standard way of handling this.</p>
|
<p>At least in the Java version of Lucene, you could write yourself a recursive function that digs through the BooleanQuery Query objects that the QueryParser will build; every time it finds a TermQuery, it could replace it with a BooleanQuery that OR's the original term with the new term you want added into the query.</p>
| 22,968
|
<p>I'm writing a simple photo album app using ASP.NET Ajax.<br>
The app uses async Ajax calls to pre-load the next photo in the album, without changing the URL in the browser.</p>
<p>The problem is that when the user clicks the <strong>back</strong> button in the browser, the app doesn't go back to the previous photo, instead, it navigates to the home page of the application.</p>
<p>Is there a way to trick the browser into adding each Ajax call to the browsing history?</p>
|
<p><strong>Update: There is now the HTML5 History API (pushState, popState) which deprecates the HTML4 <code>hashchange</code> functionality. <a href="https://github.com/balupton/history.js" rel="nofollow noreferrer">History.js</a> provides cross-browser compatibility and an <a href="https://github.com/balupton/history.js/wiki/Intelligent-State-Handling" rel="nofollow noreferrer">optional</a> <code>hashchange</code> fallback for HTML4 browsers.</strong></p>
<p>The answer for this question will be more or less the same as my answers for these questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/3205900/how-to-show-ajax-requests-in-url/3276206#3276206">How to show Ajax requests in URL?</a></li>
<li><a href="https://stackoverflow.com/questions/3460041/how-does-gmail-handle-back-forward-in-rich-javascript/3460269#3460269">How does Gmail handle back/forward in rich JavaScript?</a></li>
</ul>
<p>In summary, you'll definitely want to check out these two projects which explain the whole hashchange process and adding ajax to the mix:</p>
<ul>
<li><p><a href="https://github.com/browserstate/history.js" rel="nofollow noreferrer">jQuery History</a> (using hashes to manage your pages state and bind to changes to update your page). </p></li>
<li><p><a href="https://github.com/balupton/jquery-ajaxy" rel="nofollow noreferrer">jQuery Ajaxy</a> (ajax extension for jQuery History, to allow for complete ajax websites while being completely unobtrusive and gracefully degradable).</p></li>
</ul>
|
<p>The 3.5 SP1 update has support for browser history and back button in ASP.NET ajax now.</p>
| 4,974
|
<p>I would like to create an SSL connection for generic TCP communication. I think I figured out how to do it in the code, using the info here: <a href="http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx</a>
What I'm having trouble with is creating a cert so I can test this out. I tried makecert.exe testCert, and that created a cert, but apparently it doesn't have a private key associated with it. So what I'm looking for is the simplest procedure to create a cert and get the connection to work.</p>
|
<p>I haven't found a <em>simple</em> way to do this yet, but I found <a href="http://www.herongyang.com/crypto/openssl_crt.html" rel="nofollow noreferrer">this site</a> helpful a few months back.</p>
<p>O'Reilly also published a book called Network Security Hacks (available on Safari) that has a section starting at Hack #45 on creating your own certificate authority.</p>
|
<p>For anybody else attempting this the pkcs12 certificate created as detailed here <a href="https://stackoverflow.com/questions/440762/openssl-command-line-troubles">openssl question</a> and using the X509Certificate2.CreateFromCertFile method gets past the private key problem. Note I used openssl with cygwin on Windows.</p>
| 4,114
|
<p>I have 3 projects in my VS solution. One of them is a Web app, the second one is a Windows Service and the last one a Setup project for my Web app. </p>
<p>What I want is by the end of the installation of the web app in my setup project, within my custom action to try and install my windows service given that I have the location of the assembly by then.</p>
|
<p>Ok, here is what REALLY worked for me, it has been tested on multiple machines with different OS ( Vista, XP, Win2k, Win2003 server )</p>
<p>The code has been taken from <a href="http://www.tech-archive.net/Archive/VB/microsoft.public.vb.winapi/2006-08/msg00238.html" rel="noreferrer">here</a> so full credit goes to whoever wrote this piece of code.</p>
<p>Once you add the dll or source file into your project make sure to add the ServiceTools namespace and then you have access to some very handy functionality such as...</p>
<pre><code>//Installs and starts the service
ServiceInstaller.InstallAndStart("MyServiceName", "MyServiceDisplayName", "C:\\PathToServiceFile.exe");
//Removes the service
ServiceInstaller.Uninstall("MyServiceName");
//Checks the status of the service
ServiceInstaller.GetServiceStatus("MyServiceName");
//Starts the service
ServiceInstaller.StartService("MyServiceName");
//Stops the service
ServiceInstaller.StopService("MyServiceName");
//Check if service is installed
ServiceInstaller.ServiceIsInstalled("MyServiceName");
</code></pre>
<p>I hope this helps.</p>
|
<p>Use below code to install windows service using C#:</p>
<pre><code>public void InstallWinService(string winServicePath)
{
try
{
ManagedInstallerClass.InstallHelper(new string[] { winServicePath});
}
catch (Exception)
{
throw;
}
}
</code></pre>
| 46,773
|
<p>I'm trying to create a dialog box using C++ and the windows API, but I don't want the dialog defined in a resource file. I can't find anything good on this on the web, and none of the examples I've read seem to define the dialog programmatically.</p>
<p>How can I do this?</p>
<p>A simple example is fine. I'm not doing anything complicated with it yet.</p>
|
<p>Raymond Chen wrote a few posts about the dialog manager:</p>
<ul>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050329-00/?p=36043" rel="nofollow noreferrer">The dialog manager, part 1: Warm-ups</a></li>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050330-00/?p=36023" rel="nofollow noreferrer">The dialog manager, part 2: Creating the frame window</a></li>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050331-00/?p=36003" rel="nofollow noreferrer">The dialog manager, part 3: Creating the controls</a></li>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050401-00/?p=35993" rel="nofollow noreferrer">The dialog manager, part 4: The dialog loop</a></li>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050404-48/?p=35983" rel="nofollow noreferrer">The dialog manager, part 5: Converting a non-modal dialog box to modal</a></li>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050405-46/?p=35973" rel="nofollow noreferrer">The dialog manager, part 6: Subtleties in message loops</a></li>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050406-57/?p=35963" rel="nofollow noreferrer">The dialog manager, part 7: More subtleties in message loops</a></li>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050407-00/?p=35953" rel="nofollow noreferrer">The dialog manager, part 8: Custom navigation in dialog boxes</a></li>
<li><a href="https://devblogs.microsoft.com/oldnewthing/20050408-41/?p=35943" rel="nofollow noreferrer">The dialog manager, part 9: Custom accelerators in dialog boxes</a></li>
</ul>
|
<p>Take a look at <a href="http://www.codeproject.com/KB/wtl/resourcelessdialogtoolkit.aspx" rel="nofollow noreferrer">this toolkit</a> that describes how to create dialogs without resource files.</p>
<p>It's in WTL. However, I'm sure you can pick apart the internals to achieve the same thing using the Win32 API directly.</p>
| 8,685
|
<p>I have an Java desktop application which connects directly with the DB (an Oracle). The application has multiple user accounts. What is the correct method to send the user's password (not DB password) over the network? I don't want to send it in plain text.</p>
|
<p>You could connect over a secure socket connection, or hash the password locally before sending it to the database (or better, both) - Ideally, the only time the password should exist in plain text form is prior to hashing. If you can do all of that on the client side, more the better.</p>
|
<p>If you don't want to send the data in plain text, use encryption !!!</p>
<p>Use some encryption algorithm such as AES, Twofish etc.</p>
<p>You must also take into consideration where your client and server are. If they both are in the same machine, there is no use of using an encryption. If they are in different machines, use some encryption algorithm to send sensitive data.</p>
<p>If YOU are checking the validity of the passwords, you can just send the hash of the password. Beware that this method will work only if you are comparing the password yourself. If some other application (out of your control) is doing the validation job, you cannot hash the password.</p>
| 9,558
|
<p>I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution?</p>
|
<p>GACUTIL doesn't register DLLs -- not in the "COM" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL "register a folder" (not that you can do that with RegSvr32 either).</p>
<p>You can use a batch FOR command such as:</p>
<pre><code>FOR %a IN (C:\MyFolderWithAssemblies\*.dll) DO GACUTIL /i %a
</code></pre>
<p>If you place that in a batch file, you must replace %a with %%a</p>
|
<p>Use </p>
<blockquote>
<p>gacutil /il YourPathTo_A_TextFile.txt</p>
</blockquote>
<p>switch, if you have dlls in multiple different folders. Otherwise go with the <code>for ... in</code> loop mentioned by Euro.</p>
<p>The text file should contain a list of assembly paths (one path per line) which should be installed. The paths can also be different folders all over the system.
Run the command line as an administrator!</p>
<p><strong>Here an example of the YourPathTo_A_TextFile.txt:</strong></p>
<blockquote>
<p>C:\...Microsoft.Practices.EnterpriseLibrary.Common.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Configuration.Design.HostAdapter.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Configuration.Design.HostAdapterV5.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Configuration.DesignTime.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Configuration.EnvironmentalOverrides.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Data.dll</p>
</blockquote>
| 5,544
|
<p>I need to update a field (which is currently empty) based on a match with another table. This should be simple, but my syntax is wrong.</p>
<p>In SQLServer 2005, the syntax would be </p>
<pre><code>UPDATE Facilities-NOID
SET Facilities-NOID.ID = Facilities-ID.ID
FROM Facilities-NOID, Facilities-ID
WHERE [Facilities-ID].[Structure ID] = [Facilities-NOID].[Structure ID];
</code></pre>
<p>Access doesn't like that FROM line, but if I leave it out, it wants each ID. This should be simple, but I'm not seeing it in the MS help on the Update syntax.</p>
|
<p>I think this is what you want:</p>
<pre><code>UPDATE Facilities-NOID
INNER JOIN Facilities-ID ON Facilities-NOID.[Structure ID]
= Facilities-ID.[Structure ID]
SET Facilities-NOID.ID= Facilities-ID.ID
</code></pre>
<p>You are updating Facilities-NOID based on a match on Structure ID occurring in Facilities-ID.</p>
|
<p>Remove the FROM clause completely</p>
<pre><code>UPDATE Facilities-NOID
SET Facilities-NOID.ID = Facilities-ID.ID
WHERE [Facilities-ID].[Structure ID] = [Facilities-NOID].[Structure ID];
</code></pre>
<p>(that's the way that the query builder ends up constructing them)</p>
| 49,629
|
<p>Is it possible to do 3.1 or 5.1 audio using Flash? We're starting a project here for an interactive kiosk, and we've been told to use Flash. However, we also have a requirement to support either 3.1 or 5.1 audio (where 5.1 is the most wanted feature). </p>
<p>I haven't done any high-tech audio stuff using Flash, so I was wondering if anyone knew if it was possible to do?</p>
<p>Thanks.</p>
|
<p>A quick google search gave me this forum <a href="http://board.flashkit.com/board/showthread.php?t=715062" rel="nofollow noreferrer">http://board.flashkit.com/board/showthread.php?t=715062</a> where they state that Flash is unable to handle 5.1 audio and the alternative is to use another application that can communicate with Flash to handle the audio side of things.</p>
<p>I also found this blog entry from Summit Projects <a href="http://summitprojectsflashblog.wordpress.com/2008/08/07/wave-theory-in-actionscript-3-part-4/" rel="nofollow noreferrer">http://summitprojectsflashblog.wordpress.com/2008/08/07/wave-theory-in-actionscript-3-part-4/</a> where they go into great detail about byte handling and processing audio samples. I'm not sure if they are using their own actionscript libraries for this, or if they are using Adobe's libraries. I'm not too up to speed on the audio side of Flash with respects to surround sound.</p>
<p>I think your two options might have to be either using a separate application to run your audio(which may be less stressful) or maybe getting in touch with the Summit people if you are as lost as I am over some of the concepts they touch on, heh. Good luck!</p>
|
<p>As far as I know this is not possible. </p>
<p>You <strong>might</strong> be able to do it if you use uncompressed wave files already encoded in DTS or something and put a surround receiver in between. This will however stop you from doing anything with the sound before outputting it, not even changing the volume. And I guess that's not an option?
I think going with an external application for sound would be your best choice, maybe you can do something using Director.</p>
| 5,531
|
<p>I'm looking for a way to configure a DB connection at runtime; specifically using the Enterprise Library. I see that there's a *.Data.Configuration (or something close to this ... don't recall off the top of my head) assembly but am finding not much on the interwebs. Complicating matters is the fact that the API help is broken on Vista.</p>
<p>Now, I found this work-around:</p>
<pre><code>Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings connection = new ConnectionStringSettings();
connection.Name = "Runtime Connection";
connection.ProviderName = "System.Data.OleDb";
connection.ConnectionString = "myconstring";
cfg.ConnectionStrings.ConnectionStrings.Add(connection);
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
var runtimeCon = DatabaseFactory.CreateDatabase("Runtime Connection");
</code></pre>
<p>And although it gives me what I want, it permanently edits the App.config. Sure I can go back and delete the changes, but I'd rather not go through this hassle.</p>
|
<p>If you're using a winforms app you could try using <a href="http://msdn.microsoft.com/en-us/library/aa221771(office.11).aspx" rel="nofollow noreferrer">UserProperties</a> to store this info. Another possible solution could be <a href="http://msdn.microsoft.com/en-us/library/2tw134k3.aspx" rel="nofollow noreferrer">custom configuration sections</a>.</p>
|
<p>If you don't want it saved, you do not need to execute the cfg.Save command. </p>
<p>The Configuration object will store your changes until it isn't needed anymore.</p>
| 3,650
|
<p>What is the best way to set the time on a remote machine remotely? The machine is running Windows XP and is receiving the new time through a web service call. The goal is to keep the remote machines in synch with the server. The system is locked down so that our web service is the only access, so I cannot use a time server on each remote machine.</p>
|
<p>I would use Windows built-in internet time abilities. You can set up a <a href="http://en.wikipedia.org/wiki/Time_server" rel="nofollow noreferrer">time server</a> on your server, have it get time from a 2nd-tier timeserver, and have all your client machines get time from it.</p>
<p>I've been down the application-setting-system-time road before.</p>
|
<p>You could also probably do this in a batch file using some combination of</p>
<pre><code>TIME
</code></pre>
<p>to set the time, and</p>
<pre><code>net time \\server_name
</code></pre>
<p>to retrieve the time from a server.</p>
| 25,103
|
<p>All, </p>
<p>I currently have two projects that are under SourceSafe that I am unable to migrate to our SVN server for a number of reasons. </p>
<p>However I am currently in the process of trying to merge fixes from one project into the other. </p>
<p>I know Sourcesafe isn't the best at this but the process I am going through just now is particularly tedious</p>
<ol>
<li>Compare the files identyfying the
changes I need to merge. </li>
<li>copy and
paste the relevant changes into the
desired project</li>
<li>Test</li>
<li>Commit</li>
</ol>
<p>This doesn't seem too bad but with multiple changes and multiple files that need reviewed this is becoming a nightmare. </p>
<p>Does anyone have any other methods to carry this out??</p>
|
<p>It might be worthwhile to check out the different versions and use a 3rd-party tool to merge them. Take a look at kdiff3 (<a href="http://kdiff3.sourceforge.net" rel="nofollow noreferrer">http://kdiff3.sourceforge.net/</a>) -- it runs on linux or Windows and will merge up to 3 different versions quite intelligently. This allows you to compare two developers' changes to a common base version.</p>
<p>Another useful tool is kompare, which does an admirable job of highlighting very specific differences between two files.</p>
<p>Good luck!</p>
|
<p>winmerge can combine with sourcesafe.
support folder comparision.</p>
| 28,396
|
<pre>
create table person
(
name varchar(15),
attr1 varchar(15),
attr2 varchar(1),
attr3 char(1),
attr4 int
)
</pre>
<p>How I can use basic ORM in Perl by taking a simple table like the one above and mapping it to Perl objects? Next I'd like to perform basic operations like select results using some criteria system Perl like syntax. eg.:</p>
<pre><code>@myResults = findAll(attr1 == 3 && attr2 =~ /abc/);
</code></pre>
|
<p>Rule #1, don't write your own.</p>
<p>There are quite a number of ORMs on CPAN, including ...</p>
<ul>
<li><a href="http://search.cpan.org/dist/DBIx-Class" rel="noreferrer">DBIx::Class</a> - probably #1 in popularity at the moment</li>
<li><a href="http://search.cpan.org/dist/Rose-DB-Object" rel="noreferrer">Rose::DB::Object</a></li>
<li><a href="http://search.cpan.org/dist/Fey-ORM" rel="noreferrer">Fey::ORM</a> - my own contribution, most notable for being <a href="http://moose.perl.org/" rel="noreferrer">Moose</a>-based, which means you get all the power of Moose in your ORM-based classes.</li>
</ul>
|
<p>(Chiming late) Data::ObjectDriver (also on CPAN) provides great flexibility especially if partitioning and caching is on the list of your requirements.</p>
| 35,610
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.