Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What are some recommended frameworks for manipulating spatial data in C++?
I'm looking for a polygon object, point object, and some operations like union, intersection, distance, and area. I need to enter coordinates in WGS84 (lon,lat) and get area in square km.
I would prefer a free/open source framework, but am open to suggestions.
Edit: Unfortunately I need a non-GPL solution. LGPL is alright. | [GEOS](http://trac.osgeo.org/geos/) is an open source (LGPL) C++ geometry / topology engine. Might suit you?
Useful places to look for this stuff are this [useful article](http://www.oreillynet.com/pub/a/network/2005/06/10/osgeospatial.html) on the O'Reilly website and also [OSGeo](http://www.osgeo.org/) which is a collaboration to support open source geospatial stuff. | I also recommend [Generic Geometry Library](http://trac.osgeo.org/ggl/) which recently has been [reviewed](http://permalink.gmane.org/gmane.comp.lib.boost.announce/239) and eventually accepted to the collection of [Boost C++ Libraries](http://permalink.gmane.org/gmane.comp.lib.boost.announce/246). As included in Boost, the GGL is now called Boost.Geometry, more precisely *Boost.Geometry aka GGL, Generic Geometry Library*.
Other useful tools
* [ORFEO Toolbox](http://www.orfeo-toolbox.org/) (aka OTB) - a library of image processing algorithm
* [MetaCRS](http://metacrs.osgeo.org/) - a project encompassing several projections, and coordinate system related technologies.
* [libgeotiff](http://trac.osgeo.org/geotiff/) for sole GeoTIFF manipulation | What are some recommended frameworks for manipulating spatial data in C++? | [
"",
"c++",
"geospatial",
"polygon",
"spatial",
""
] |
I call the following function with a mouseover event but it's not working. My id's are all correct & I have properly linked all my external scripts.
```
function new2() {
var prevWin = document.GetElementById("recentlyaddedtip");
prevWin.style.visibility = "visible";
}
```
recentlyaddedtip is set as hidden in the stylesheet (and it properly changes to visible when I change it manually.) | JavaScript is case sensitive.
Try:
```
document.getElementById('recentlyaddedtip');
```
Notice the small 'g'. | You shouldn't uppercase the G in GetElementById, it should be getElementById().
JavaScript is case sensitive ;-) | getElementById problem | [
"",
"javascript",
""
] |
I've got a simple JavaScript regex check (written by other developer) that works perfectly on thousands of different strings. However I've just discovered one particular string value that's causing that regex to take as long as 10min to execute in Firefox/IE which is unacceptable. I've extracted an actual regex call into small code snippet for your convenience:
```
<html>
<script>
function dodo(){
var mask = /^([\w'#@\-\&\(\)\/.]+[ ]*){1,100}$/;
var value = "Optometrists Association Australia, Queensland/NT Division";
mask.exec(value);
}
</script>
<body>
<input type="button" value="Click" onclick="dodo()">
</body>
</html>
```
What is the problem here? If I change value to anything else it works perfectly.
Thank you! | This looks like a poor application for a regex, and a poor regex to boot. The intent seems to be to match a list of between 1 and 100 space-separated "words", I think. Here are the core problems I can see:
1. The use of "[ ]\*" at the end of the word, instead of "[ ]+" means that every byte can potentially be a "word" alone, whether it's bounded by spaces or not. That's a lot of match cases for your engine to keep track of.
2. You're using capturing parentheses ("(...)") instead non-capturing ones ("(?:...)"). The grouping will be doing yet more bookeeping to save the last word matched for you, which you probably doing need or not.
And some minor issues:
3. The "[ ]\*" expression is redundant. Just use " \*" to match zero or more spaces. But you probably want "\s" there, to match whitespace of any type, not just a space.
4. The expression allows whitespace at the end of the string, but not the beginning. Most applications usually want to tolerate both or neither.
5. For readability, don't use backslash escaping where it's not needed. Only the "-" in your bracket actually needs it.
6. What's magic about 100? Do you really want to hard-code that limit?
Finally, why use a regex here at all? Why not simply split() on whitespace into an array of substrings, and then test each resulting word against a simpler expression? | You probably meant to have a + after the space group, rather than \*. If you replace it back with a +, things go much faster. The \* causes the regex evaluator to try a huge number of combinations, all of which fail when they reach the ','. You might want to add a ',' to the first character group too.
Overall, it might look like this:
```
var mask = /^([\w'#@\-\&\(\)\/.,]+[ ]+){1,100}$/;
``` | JavaScript regex exec takes too long to execute | [
"",
"javascript",
"regex",
"internet-explorer",
"firefox",
"browser",
""
] |
I have no experience with low level programing and I need this piece of code to not use [StructLayout(LayoutKind.Explicit)]. My site runs on a shared host and in medium trust.
So it won't run if this code is in there.
**Update:**
I'm using this inside a Octree to Quantize a png file.
Does anyone know a work around?
**Update**
New question here => [Is there any way to do Image Quantization safely and with no Marshalling?](https://stackoverflow.com/questions/1099655/is-there-any-way-to-do-image-quantization-safely-and-with-no-marshalling)
```
/// <summary>
/// Struct that defines a 32 bpp colour
/// </summary>
/// <remarks>
/// This struct is used to read data from a 32 bits per pixel image
/// in memory, and is ordered in this manner as this is the way that
/// the data is layed out in memory
/// </remarks>
[StructLayout(LayoutKind.Explicit)]
public struct Color32
{
public Color32(IntPtr pSourcePixel)
{
this = (Color32)Marshal.PtrToStructure(pSourcePixel, typeof(Color32));
}
/// <summary>
/// Holds the blue component of the colour
/// </summary>
[FieldOffset(0)]
public byte Blue;
/// <summary>
/// Holds the green component of the colour
/// </summary>
[FieldOffset(1)]
public byte Green;
/// <summary>
/// Holds the red component of the colour
/// </summary>
[FieldOffset(2)]
public byte Red;
/// <summary>
/// Holds the alpha component of the colour
/// </summary>
[FieldOffset(3)]
public byte Alpha;
/// <summary>
/// Permits the color32 to be treated as an int32
/// </summary>
[FieldOffset(0)]
public int ARGB;
/// <summary>
/// Return the color for this Color32 object
/// </summary>
public Color Color
{
get { return Color.FromArgb(Alpha, Red, Green, Blue); }
}
}
``` | Marshal.PtrToStructure Method (IntPtr, Type) won't work anyway since it requires
> ```
> [SecurityPermissionAttribute(
> SecurityAction.LinkDemand,
> Flags = SecurityPermissionFlag.UnmanagedCode)]
> ```
You could deal with the offsets yourself safely, but you would have to do it without using Marshal.
I suggest also moving to using uints for simplicity.
```
public struct Color32
{
const uint BlueMask = 0xFF000000;
const uint GreenMask = 0x00FF0000;
const uint RedMask = 0x0000FF00;
const uint AlphaMask = 0x000000FF;
const int BlueShift = 24;
const int GreenShift = 16;
const int RedShift = 8;
const int AlphaShift = 0;
private byte GetComponent(uint mask, int shift)
{
var b = (this.ARGB & mask);
return (byte) (b >> shift);
}
private void SetComponent(int shift, byte value)
{
var b = ((uint)value) << shift
this.ARGB |= b;
}
public byte Blue
{
get { return GetComponent(BlueMask, BlueShift); }
set { SetComponent(BlueShift, value); }
}
public byte Green
{
get { return GetComponent(GreenMask, GreenShift); }
set { SetComponent(GreenShift, value); }
}
public byte Red
{
get { return GetComponent(RedMask, RedShift); }
set { SetComponent(RedShift, value); }
}
public byte Alpha
{
get { return GetComponent(AlphaMask, AlphaShift); }
set { SetComponent(AlphaShift, value); }
}
/// <summary>
/// Permits the color32 to be treated as an UInt32
/// </summary>
public uint ARGB;
/// <summary>
/// Return the color for this Color32 object
/// </summary>
public Color Color
{
get { return Color.FromArgb(Alpha, Red, Green, Blue); }
}
}
```
however it would appear that what you want to do is convert an int32 in one byte order to the reverse.
For this you have [System.Net.IPAddress.HostToNetworkOrder](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.hosttonetworkorder.aspx) (nasty usage in this regard, you are simply using it to reverse the endianess rather than being specific about which ordering you intend)
so if you could read your input data as simple int32 values then do:
```
static Color FromBgra(int bgra)
{
return Color.FromArgb(System.Net.IPAddress.HostToNetworkOrder(bgra));
}
```
This would likely be much simpler. | Interoperating with native code and memory is an inherently unsafe operation. Any calls to the Marshal class will fail as well. You can't access the memory, or do any Interop unless you have full trust level. | Replace [StructLayout] with something that doesn't use System.Runtime.InteropServices? | [
"",
"c#",
"asp.net",
"data-structures",
"image",
"unmanaged",
""
] |
I'm trying to learn web development in Java and, from what I have seen so far, I think it's easy to get lost in the endless numbers of libraries, frameworks, techniques available.
Too many books focus on some specific component (Spring, Hibernate, JSP, ...) and give only "hello world" examples.
I'm looking for books or web resources that let you understand the whole picture and provide "real world" examples, including several frameworks, techniques, in the same example.
Can you recommend any book?
Thanks! | I like [POJOs in action](http://www.manning.com/crichardson/) because (besides is kinda old) it explains clearly the approach of the emerging applications using POJOs and therefore Spring, Hibernate and many other popular frameworks | Java Web development is a very huge field. I have read several books on the topic, but find this one very helpful for the basics of Java web development in general:
Bryan Basham: "Head First Servlets and JSP: Passing the Sun Certified Web Component Developer Exam" (Paperback)
It covers the foundations on which all the Java web frameworks build upon (web application container, environment, deployment, lifecycle...) in a very accessible way, however: it does not give you an overview over the huge amount of frameworks that are available. As another answer mentions, you probably want to narrow the scope, most frameworks have an area they solve differently and which they solve better than others (e.g. component-based, MVC,...). | Resources to learn and understand state-of-the-art web development in Java? | [
"",
"java",
""
] |
```
Class someInterface = Class.fromName("some.package.SomeInterface");
```
How do I now create a new class that implements `someInterface`?
I need to create a new class, and pass it to a function that needs a `SomeInterface` as an argument. | Creating something which pretends to implement an interface on the fly actually isn't too hard. You can use [`java.lang.reflect.Proxy`](http://java.sun.com/javase/6/docs/api/java/lang/reflect/Proxy.html) after implementing [`InvocationHandler`](http://java.sun.com/javase/6/docs/api/java/lang/reflect/InvocationHandler.html) to handle any method calls.
Of course, you could actually generate a real class with a library like [BCEL](http://jakarta.apache.org/bcel/).
If this is for test purposes, you should look at mocking frameworks like [jMock](http://www.jmock.org/) and [EasyMock](http://easymock.org/). | Easily, [`java.lang.reflect.Proxy`](http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html) to the rescue!
**Full working example**:
```
interface IRobot {
String Name();
String Name(String title);
void Talk();
void Talk(String stuff);
void Talk(int stuff);
void Talk(String stuff, int more_stuff);
void Talk(int stuff, int more_stuff);
void Talk(int stuff, String more_stuff);
}
public class ProxyTest {
public static void main(String args[]) {
IRobot robot = (IRobot) java.lang.reflect.Proxy.newProxyInstance(
IRobot.class.getClassLoader(),
new java.lang.Class[] { IRobot.class },
new java.lang.reflect.InvocationHandler() {
@Override
public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) throws java.lang.Throwable {
String method_name = method.getName();
Class<?>[] classes = method.getParameterTypes();
if (method_name.equals("Name")) {
if (args == null) {
return "Mr IRobot";
} else {
return args[0] + " IRobot";
}
} else if (method_name.equals("Talk")) {
switch (classes.length) {
case 0:
System.out.println("Hello");
break;
case 1:
if (classes[0] == int.class) {
System.out.println("Hi. Int: " + args[0]);
} else {
System.out.println("Hi. String: " + args[0]);
}
break;
case 2:
if (classes[0] == String.class) {
System.out.println("Hi. String: " + args[0] + ". Int: " + args[1]);
} else {
if (classes[1] == String.class) {
System.out.println("Hi. int: " + args[0] + ". String: " + args[1]);
} else {
System.out.println("Hi. int: " + args[0] + ". Int: " + args[1]);
}
}
break;
}
}
return null;
}
});
System.out.println(robot.Name());
System.out.println(robot.Name("Dr"));
robot.Talk();
robot.Talk("stuff");
robot.Talk(100);
robot.Talk("stuff", 200);
robot.Talk(300, 400);
robot.Talk(500, "stuff");
}
}
``` | Java Reflection: Create an implementing class | [
"",
"java",
"reflection",
"interface",
""
] |
I was wondering (and used Google with no clear result) if there is any way to connect to a MySQL database with PHP using a hashed password. Say I have the following:
```
Password (plain): 'foobar'
Password (sha1): '8843d7f92416211de9ebb963ff4ce28125932878'
```
Now I would like to connect to MySQL like this (using the mysql\_\* function as example, I'm using PDO though):
```
$db_link = mysql_connect ( 'localhost', 'user', '8843d7f92416211de9ebb963ff4ce28125932878' );
```
I this possible? Have anyone done this before? | The short answer is no.
But, just wondering... what is your real concern? Someone hacking into your server and discovering your password? | Then the "hash" would *be* the password. What would be the benefit? | Connect to MySQL with hashed password? | [
"",
"php",
"mysql",
"hash",
"connection",
""
] |
I have an array of custom objects. MyCustomArr[]. I want to convert this to System.Array so that I can pass it to a method that accepts only System.Array. The signature of the method is:
```
public void Load(Array param1, string param2)
{
}
``` | No conversion is needed for that as far as I know. You can simply go ahead and pass your array to the method. The following code works out well:
```
MyClass[] myClassArray = new MyClass[2];
myClassArray[0] = new MyClass();
myClassArray[1] = new MyClass();
Load(myClassArray, "some text");
``` | What do you want to do with the array? The code below builds and runs, so I'm not sure where your problem lies:
```
public class MyClass
{
public class MyObject
{
}
public static void RunSnippet()
{
MyObject[] objects = new MyObject[5];
Test(objects);
}
private static void Test(System.Array obj)
{
System.Console.WriteLine("Count: " + obj.Length.ToString());
}
}
``` | Convert a custom object array to System.Array in C# | [
"",
"c#",
".net",
""
] |
Trying to extract strings that are wrapped in double brackets. For example [[this is one token]] that should be matched. To make things more elegant, there should be an escape sequence so that double bracketed items like \[[this escaped token\]] don't get matched.
The pattern `[^\\\\]([\\[]{2}.+[^\\\\][\\]]{2})` with "group 1" to extract the token is close, but there are situations where it doesn't work. The problem seems to be that the first "not" statement is being evaluated as "anything except a backslash". The problem is, "anything" is not including "nothing". So, what would make this pattern match "nothing or any character other than a backslash"?
Here is a unit test to show the desired behavior:
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
public class RegexSpike extends TestCase {
private String regex;
private Pattern pattern;
private Matcher matcher;
@Override
protected void setUp() throws Exception {
super.setUp();
regex = "[^\\\\]([\\[]{2}.+[^\\\\][\\]]{2})";
pattern = Pattern.compile(regex);
}
private String runRegex(String testString) {
matcher = pattern.matcher(testString);
return matcher.find() ? matcher.group(1) : "NOT FOUND";
}
public void testBeginsWithTag_Passes() {
assertEquals("[[should work]]", runRegex("[[should work]]"));
}
public void testBeginsWithSpaces_Passes() {
assertEquals("[[should work]]", runRegex(" [[should work]]"));
}
public void testBeginsWithChars_Passes() {
assertEquals("[[should work]]", runRegex("anything here[[should
work]]"));
}
public void testEndsWithChars_Passes() {
assertEquals("[[should work]]", runRegex("[[should
work]]with anything here"));
}
public void testBeginsAndEndsWithChars_Passes() {
assertEquals("[[should work]]", runRegex("anything here[[should
work]]and anything here"));
}
public void testFirstBracketsEscaped_Fails() {
assertEquals("NOT FOUND", runRegex("\\[[should NOT work]]"));
}
public void testSingleBrackets_Fails() {
assertEquals("NOT FOUND", runRegex("[should NOT work]"));
}
public void testSecondBracketsEscaped_Fails() {
assertEquals("NOT FOUND", runRegex("[[should NOT work\\]]"));
}
}
``` | You can simply use `(^|[^\\])`, which will *either* match the beginning of a string (provided you set the `MULTILINE` mode on your regex) *or* a single character that is not a backslash (including spaces, newlines, etc.).
You'll also want to replace `.+` with `.+?`, because otherwise a string such as `"[[one]] and [[two]]"` will be seen as a single match, where `"one]] and [[two"` is considered to be between brackets.
A third point is that you do not have to wrap a single character (even escaped ones such as `\[` or `\]`) in a character class with `[]`.
So that would make the following regex (pardon me removing the double-escapedness for clarity):
```
(^|[^\\])(\[{2}.+?[^\\]\]{2})
```
*(Also note that you cannot escape the escape character with your regex. Two slashes before a `[` will not be parsed as a single (escaped) slash, but will indicate a single (unescaped) slash and an escaped bracket.)* | What should happen with this string? (Actual string content, not a Java literal.)
```
foo\\[[blah]]bar
```
What I'm asking is whether you're supporting escaped backslashes. If you are, the lookbehind won't work. Instead of looking for a single backslash, you would have to check for on odd but unknown number of them, and Java lookbehinds can't be open-ended like that. Also, what about escaped brackets *inside* a token--is this valid?
```
foo[[blah\]]]bar
```
In any case, I suggest you come at the backslash problem from the other direction: match any number of escaped characters (i.e. backslash plus anything) immediately preceding the first bracket as part of the token. Inside the token, match any number of characters other than square brackets or backslashes, or any number of escaped characters. Here's the actual regex:
```
(?<!\\)(?:\\.)*+\[\[((?:[^\[\]\\]++|\\.)*+)\]\]
```
...and here it is as a Java string literal:
```
"(?<!\\\\)(?:\\\\.)*+\\[\\[((?:[^\\[\\]\\\\]++|\\\\.)*+)\\]\\]"
``` | RegEx in Java not working as I expected | [
"",
"java",
"regex",
""
] |
In a Java application stack with Spring & Hibernate (JPA) in the Data Access Layer, what are good methods of applying the password encryption (hopefully using annotations), and where can you find out more about getting it done (tutorial, etc)?
It's understood that I would use a [JCA](http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html) supported algorithm for encrypting the passwords, but I would prefer to not have to implement the wrapper logic if there is an easy way.
I was looking at Jasypt, and was a) wondering if that's a good option and how to do it and b) what else people are using for this. If anyone is using Jasypt or an alternative, details of your experience it would be great. | Java has all of the required libraries already provided for you. Simply create a utility method that implements hashing with a salt as described at [OWASP](http://www.owasp.org/index.php/Hashing_Java "OWASP").
If you really don't want to own that code and don't mind an extra dependency, it seems that the [Shiro](http://shiro.apache.org "Shiro") library (formerly [JSecurity](http://www.jsecurity.org/ "JSecurity")) has an [implementation](http://www.jsecurity.org/api/org/jsecurity/crypto/hash/package-summary.html "JSecurity Hashing Utilities") of what is described by OWASP.
It also looks like the JASYPT library you mentioned has a [similar utility](http://www.jasypt.org/api/jasypt/apidocs/org/jasypt/digest/StandardStringDigester.html "JASYPT Hashing").
I realize that this answer doesn't mention Spring or Hibernate but I'm not clear how you are hoping to utilize them in this scenario. | You can use [Jasypt with Hibernate](http://www.jasypt.org/hibernate3.html) to encrypt or hash your properties on the fly if thats what you're looking for. The actual algorithm for computing digests (hashes) is pretty simple using the JCE if you want to roll your own as well. | Password encryption with Spring/Hibernate - Jasypt or something else? | [
"",
"java",
"hibernate",
"jpa",
"password-encryption",
"jasypt",
""
] |
Consider the following code:
```
@Entity
@Table(name = "a")
public class A implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
public int id;
@Transient
public B b;
public B getB()
{
return B;
}
}
```
When I fetch A, I'm manually filling B (another hibernate entity). If I try and access by by using a.b, then it fails, but, if I user a.getB(); then it succeeds.
Why is this? | 1. Class members should ever be private!
2. If your object is attached to the Hibernate Session, you're working on a proxy. So, if you like to access your class member directly (which is bad!), you have to detach the object first. | Sounds like a lazy fetching issue. The public reference is null when you try to access it directly, but when you do it with "get", Hibernate knows to call out to the database and hydrate that instance for you. | Hibernate not fetching public member | [
"",
"java",
"hibernate",
"transient",
""
] |
I'm looking for an e-commerce "platform" in Java or .NET that can satisfy the following requirements:
* Product / Service Management
* Customer Account Management
* Shopping Cart
* Checkout / Merchant Integration
* Localization (especially for currency)
* Coupons
* Multiple Storefronts
* Reporting
* Possible PayPal / Google Checkout Integration
The goal here is to integrate this with a RIA written in Adobe Flex. We are comfortable with writing a thin backend layer to support the Flex app, so the solution doesn't require a remotely-accessible API, rather just one that we can invoke from our own backend code. | I used ofbiz for some projects, a joyful experience. It's now under the apache umbrella: <http://ofbiz.apache.org/>
From the website:
> The Apache Open For Business Project
> is an open source enterprise
> automation software project licensed
> under the Apache License Version 2.0.
> By open source enterprise automation
> we mean: Open Source ERP, Open Source
> CRM, Open Source E-Business /
> E-Commerce, Open Source SCM, Open
> Source MRP, Open Source CMMS/EAM, and
> so on
I used it to build an ecommerce application to sell customized products to consumers. I used the webshop part, the production planning and warehouse management.
Beware that it takes some time to dig into this huge framework but depending on your actual needs it will be worth it. There is also decent commercial support by a lot of service providers. | Look at nopCommerce - <http://www.nopCommerce.com> | Good e-commerce platform for Java or .NET | [
"",
"java",
".net",
"e-commerce",
""
] |
I can currently run either Django through mod\_wsgi or PHP on my Apache server.
My Django projects run at: <http://localhost> and source is at C:/django\_proj
My PHP projects run at: <http://php.localhost> and source is at C:/web
If I turn both on, php.localhost and localhost go to the Django project. I've already set them up through Apache virtual hosts.
Here are some relevant lines in httpd.conf:
```
DocumentRoot "C:/web"
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
<Directory "C:/web">
Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
<Directory "C:/django_proj">
Order allow,deny
Allow from all
</Directory>
Include "C:/django_proj/apache/apache_django_wsgi.conf"
```
The relevant lines in `apache_django_wsgi.conf` is:
```
WSGIScriptAlias / "C:/django_proj/apache/proj.wsgi"
<Directory "C:/django_proj/apache">
Order allow,deny
Allow from all
</Directory>
```
Inside httpd-vhosts.conf:
```
<Directory C:/web>
Order Deny,Allow
Allow from all
</Directory>
<Directory C:/django_proj>
Order Deny,Allow
Allow from all
</Directory>
<VirtualHost *:80>
DocumentRoot "C:/django_proj"
ServerName localhost
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:/web"
ServerName php.localhost
</VirtualHost>
```
My PHP project is current inaccessible. Does anyone have any ideas what I'm missing? | I run dozens of mod\_wsgi/Django sites, PHP sites, and a Rails site with a single Apache.
It's mostly done using virtual hosts but I have some that are running both on the same domain.
You just need to put your `WSGIScriptAlias /...` after any other Location/Alias directives.
Lets say, for example, I want to run phpMyAdmin on the same domain as a Django site. The config would look something like this:
```
Alias /phpmyadmin /full/path/to/phpmyadmin/
<Directory /full/path/to/phpmyadmin>
Options -Indexes
...etc...
</Directory>
WSGIScriptAlias / /full/path/to/django/project/app.wsgi
<Directory /full/path/to/django/project>
Options +ExecCGI
...etc...
</Directory>
```
**Edit**:
Your configuration should look something like this:
```
<VirtualHost *:80>
DocumentRoot "C:/django_proj"
ServerName localhost
WSGIScriptAlias / "C:/django_proj/apache/proj.wsgi"
<Directory "C:/django_proj/apache">
Options +ExecCGI
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:/web"
ServerName php.localhost
Alias / C:/web
<Directory C:/web>
Options Indexes FollowSymLinks
AllowOverride None
Order Deny,Allow
Allow from all
</Directory>
</VirtualHost>
```
You don't need those `<Directory>` directives in `http.conf`... do all your configuration in the Virtual hosts.
Also, completely get rid of the `<Directory />` block. | Your `WSGIScriptAlias / ...` directive is telling Apache that everything request starting with "/" should get fed through Django's WSGI handler. If you changed that to read `WSGIScriptAlias /django-proj/ ...` instead, only requests starting with "/django-proj" would get passed into Django.
An alternative would be to start setting up virtual hosts for each project. This way you could configure Apache to put each project at the / of it's own domain, and you wouldn't need to worry about the configuration for one project affecting one of your other projects. | How do I run Django and PHP together on one Apache server? | [
"",
"php",
"django",
"apache-config",
""
] |
I am writing a simple program, which is trying to find next palindrome number after given number.
As for now, I am stuck at this point:
```
string::iterator iter; // iterators for the string
string::iterator riter;
//testcases is a vector<string> with strings representing numbers.
for (unsigned int i = 0; i < testcases.size() ; ++i) {
iter = testcases[i].begin();
riter = testcases[i].end();
while ( !isPalin(testcases[i]) ) { //isPalin(string) is a function
//which is checking if given string
//is a palindrome
//if n-th digit from the end is different from the
//n-th digit, then I want to replace latter one, so they will
//be the same.
if ( *iter != *riter ) {
testcases[i].replace(riter, riter, *iter);
}
++iter; // advancing forward iterator;
--riter; // advancing backward iterator;
}
cout << testcases[i] << " -> ok\n";
}
```
When I am compiling this one using Microsoft Visual Studio 2008, I am getting this error:
```
Compiling...
main.cpp
.\main.cpp(53) : error C2664: 'std::basic_string<_Elem,_Traits,_Ax> &std::basic_string<_Elem,_Traits,_Ax>::replace(unsigned int,unsigned int,const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'std::_String_iterator<_Elem,_Traits,_Alloc>' to 'unsigned int'
with
[
_Elem=char,
_Traits=std::char_traits,
_Ax=std::allocator
]
and
[
_Elem=char,
_Traits=std::char_traits,
_Alloc=std::allocator
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
```
Am I doing something stupid or am I missing something?
I would be grateful for any help / suggestion. | About the code you have:
Why don't you just assign the values at the end of the two iterators?
```
if ( *iter != *riter ) {
*riter = *iter;
}
```
As Oli pointed out, there are other problems in the code, the first of which is the fact that you are setting riter to be string.end(), witch is a non-dereference-able iterator. end() iterators are always one past the end, and thus the use above will try to write beyond the assigned memory.
Maybe you should try using .rbegin() instead. It will provide a reverse iterator pointing to the last element that moves towards the beginning of the string as you increment it.
On the algorithm:
If your intention is finding the next number that is a palindrome, I am not sure that the algorithm you have implemented is correct. As an example, if the input number is 123456 the algorithm will detect that it is not a palindrome and will convert to 12345\_1\_ which is smaller than the original number. | In addition to dribeas' answer I suggest you to initialize `riter` to "`.end() - 1`" in order to avoid overindexing the string. | C++: Replacing part of string using iterators is not working | [
"",
"c++",
"visual-studio-2008",
"string",
"iterator",
""
] |
I have a PHP script that does an HTTP request on behalf of the browser and the outputs the response to the browser. Problem is when I click the links from the browser on this page it complains about cookie variables. I'm assuming it needs the browsers cookie(s) for the site.
how can I intercept and forward it to the remote site? | In fact, it is possible. You just have to take the cookie ofthe browser and pass it as a parameter to curl to mimik the browser.
It's like a session jacking...
Here is a sample code:
```
// Init curl connection
$curl = curl_init('http://otherserver.com/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// You can add your GET or POST param
// Retrieving session ID
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
// We pass the sessionid of the browser within the curl request
curl_setopt( $curl, CURLOPT_COOKIE, $strCookie );
// We receive the answer as if we were the browser
$curl_response = curl_exec($curl);
```
It works very well if your purpose is to call another website, but this will fail if you call your web server (the same that is launching the curl command). It's because your session file is still open/locked by this script so the URL you are calling can't access it.
If you want to bypass that restriction (call a page on the same server), you have to close the session file with this code before you execute the curl :
```
$curl = curl_init('http://sameserver.com/');
//...
session_write_close();
$curl_response = curl_exec($curl);
```
Hope this will help someone :) | This is how I forward all browser cookies to curl and also return all cookies for the curl request back to the browser. For this I needed to solve some problems like getting cookies from curl, parsing http header, sending multiple cookies and session locking:
```
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// get http header for cookies
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
// forward current cookies to curl
$cookies = array();
foreach ($_COOKIE as $key => $value)
{
if ($key != 'Array')
{
$cookies[] = $key . '=' . $value;
}
}
curl_setopt( $ch, CURLOPT_COOKIE, implode(';', $cookies) );
// Stop session so curl can use the same session without conflicts
session_write_close();
$response = curl_exec($ch);
curl_close($ch);
// Session restart
session_start();
// Seperate header and body
list($header, $body) = explode("\r\n\r\n", $response, 2);
// extract cookies form curl and forward them to browser
preg_match_all('/^(Set-Cookie:\s*[^\n]*)$/mi', $header, $cookies);
foreach($cookies[0] AS $cookie)
{
header($cookie, false);
}
echo $body;
``` | How to let Curl use same cookie as the browser from PHP | [
"",
"php",
"curl",
"cookies",
""
] |
The following code:
```
public interface ISomeData
{
IEnumerable<string> Data { get; }
}
public class MyData : ISomeData
{
private List<string> m_MyData = new List<string>();
public List<string> Data { get { return m_MyData; } }
}
```
Produces the following error:
> error CS0738: 'InheritanceTest.MyData'
> does not implement interface member
> 'InheritanceTest.ISomeData.Data'.
> 'InheritanceTest.MyData.Data' cannot
> implement
> 'InheritanceTest.ISomeData.Data'
> because it does not have the matching
> return type of
> 'System.Collections.Generic.IEnumerable'.
Since a List<T> implements IEnumerable<T>, one would think that my class would implement the interface. Can someone explain what the rationale is for this not compiling?
As I can see it, there are two possible solutions:
1. Change the interface to be more specific and require IList be implemented.
2. Change my class (MyData) to return IEnumerable and implement the original interface.
Now suppose I also have the following code:
```
public class ConsumerA
{
static void IterateOverCollection(ISomeData data)
{
foreach (string prop in data.MyData)
{
/*do stuff*/
}
}
}
public class ConsumerB
{
static void RandomAccess(MyData data)
{
data.Data[1] = "this line is invalid if MyPropList return an IEnumerable<string>";
}
}
```
I could change my interface to require IList to be implemented (option 1), but that limits who can implement the interface and the number of classes that can be passed into ConsumerA. Or, I could change implementation (class MyData) so that it returns an IEnumerable instead of a List (option 2), but then ConsumerB would have to be rewritten.
This seems to be a shortcoming of C# unless someone can enlighten me. | Unfortunately, the return type must match. What you are looking for is called 'return type covariance' and C# doesn't support that.
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=90909>
Eric Lippert, senior developer on C# Compiler team, mentions on his blog that they don't plan to support return type covariance.
> "That kind of variance is called
> "return type covariance". As I
> mentioned early on in this series, (a)
> this series is not about that kind of
> variance, and (b) we have no plans to
> implement that kind of variance in C#.
> "
<http://blogs.msdn.com/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx>
It's worth reading Eric's articles on covariance and contravariance.
<http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx> | For what you want to do you'll probably want to implement the interface explicitly with a class (not interface) member that returns the List instead of IEnumerable...
```
public class MyData : ISomeData
{
private List<string> m_MyData = new List<string>();
public List<string> Data
{
get
{
return m_MyData;
}
}
#region ISomeData Members
IEnumerable<string> ISomeData.Data
{
get
{
return Data.AsEnumerable<string>();
}
}
#endregion
}
```
*Edit:* For clarification, this lets the MyData class return a List when it is being treated as an instance of MyData; while still allowing it to return an instance of IEnumerable when being treated as an instance of ISomeData. | "Interface not implemented" when Returning Derived Type | [
"",
"c#",
""
] |
I've got m2m relationship like this:
```
#main table
CREATE TABLE products_product (
id integer NOT NULL,
company_id integer,
user_id integer,
type_id integer NOT NULL,
name character varying(100) NOT NULL,
description character varying(200) NOT NULL,
tags character varying(255) NOT NULL,
image character varying(200) NOT NULL
);
#intermediate table
CREATE TABLE products_ingridientbound (
id integer NOT NULL,
ingridient_id integer NOT NULL,
company_id integer NOT NULL,
price double precision NOT NULL,
active boolean NOT NULL,
"asTopping" boolean NOT NULL
);
#final m2m table
CREATE TABLE products_ingridientproductbound (
id integer NOT NULL,
product_id integer NOT NULL,
ingridient_id integer NOT NULL,
"optionValue" integer NOT NULL,
CONSTRAINT "products_ingridientproductbound_optionValue_check" CHECK (("optionValue" >= 0))
);
```
All I want to do is to get products, which has 2 (in this example) ingridient groups, one with ID in range (16, 17, 18, 19), and another in range (43, 44, 45). I want ingridient ID to be in both groups simultaneously.
My query looks like this (it's actually generated by django orm):
```
SELECT "products_product"."id","products_product"."name",
FROM "products_product"
INNER JOIN "products_ingridientproductbound"
ON ("products_product"."id" = "products_ingridientproductbound"."product_id")
WHERE ("products_ingridientproductbound"."ingridient_id" IN (16, 17, 18, 19)
AND "products_ingridientproductbound"."ingridient_id" IN (43, 44, 45)) LIMIT 21
```
It gives me 0 results, but if I run query with only one group of IN queries than it works!
Here is data in my "products\_ingridientproductbound" table. I thought that my query could return product 3, as it is in both groups (16 and 45), but now I'm confused a bit.
[Screenshot of phpPgAdmin](http://img246.imageshack.us/img246/9900/pgtable.jpg) | If I understand what you are after, doing an INNER JOIN is not what you are looking for here, I would use a [subquery](http://www.postgresql.org/docs/7.4/interactive/functions-subquery.html) instead.
You want the product id and name that have both ingredients, correct?
I didn't test this statement but it should be something like this:
```
SELECT "products_product"."id","products_product"."name",
FROM "products_product"
WHERE (
EXISTS (SELECT 1 FROM "products_ingridientproductbound" WHERE "products_product"."id" = "products_ingridientproductbound"."product_id" AND "products_ingridientproductbound"."ingridient_id" IN (16, 17, 18, 19))
AND
EXISTS (SELECT 1 FROM "products_ingridientproductbound" WHERE "products_product"."id" = "products_ingridientproductbound"."product_id" AND "products_ingridientproductbound"."ingridient_id" IN (43, 44, 45))
)
LIMIT 21
```
Edit: remove silly remark about combining, thanks jvanderh. | You ask in your two IN clauses that the same field is in two sets without common elements. Therefore you will always get a false in one of the clauses, hence your AND will be false. | SQL query with multiple "IN" on same many-to-many table | [
"",
"sql",
"postgresql",
"many-to-many",
""
] |
Suppose we are using System.Windows.Forms.Timer in a .Net application, **Is there any meaningful difference between using the Start() and Stop() methods on the timer, versus using the Enabled property?**
For example, if we wish to pause a timer while we do some processing, we could do:
```
myTimer.Stop();
// Do something interesting here.
myTimer.Start();
```
or, we could do:
```
myTimer.Enabled = false;
// Do something interesting here.
myTimer.Enabled = true;
```
If there is no significant difference, **is there a consensus in the community about which option to choose?** | As stated by both [BFree](https://stackoverflow.com/questions/1012948/using-system-windows-forms-timer-start-stop-versus-enabled-true-false/1012981#1012981) and [James](https://stackoverflow.com/questions/1012948/using-system-windows-forms-timer-start-stop-versus-enabled-true-false/1012979#1012979), there is no difference in [`Start`](http://msdn.microsoft.com/en-us/library/system.timers.timer.start(VS.71).aspx)`\`[`Stop`](http://msdn.microsoft.com/en-us/library/system.timers.timer.stop(VS.71).aspx) versus [`Enabled`](http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled(VS.71).aspx) with regards to functionality. However, the decision on which to use should be based on context and your own coding style guidelines. It depends on how you want a reader of your code to interpret what you've written.
For example, if you want them to see what you're doing as starting an operation and stopping that operation, you probably want to use `Start/Stop`. However, if you want to give the impression that you are enabling the accessibility or functionality of a feature then using `Enabled` and `true/false` is a more natural fit.
I don't think a consensus is required on just using one or the other, you really have to decide based on the needs of your code and its maintenance. | From Microsoft's Documentation:
> Calling the Start method is the same
> as setting Enabled to true. Likewise,
> calling the Stop method is the same as
> setting Enabled to false.
<http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.enabled.aspx>
So, I guess there's no difference... | Using System.Windows.Forms.Timer.Start()/Stop() versus Enabled = true/false | [
"",
"c#",
".net",
"timer",
""
] |
In my C# (3.5) application I need to get the average color values for the red, green and blue channels of a bitmap. Preferably without using an external library. Can this be done? If so, how? Thanks in advance.
Trying to make things a little more precise: Each pixel in the bitmap has a certain RGB color value. I'd like to get the average RGB values for all pixels in the image. | The fastest way is by using unsafe code:
```
BitmapData srcData = bm.LockBits(
new Rectangle(0, 0, bm.Width, bm.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppArgb);
int stride = srcData.Stride;
IntPtr Scan0 = srcData.Scan0;
long[] totals = new long[] {0,0,0};
int width = bm.Width;
int height = bm.Height;
unsafe
{
byte* p = (byte*) (void*) Scan0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
for (int color = 0; color < 3; color++)
{
int idx = (y*stride) + x*4 + color;
totals[color] += p[idx];
}
}
}
}
int avgB = totals[0] / (width*height);
int avgG = totals[1] / (width*height);
int avgR = totals[2] / (width*height);
```
Beware: I didn't test this code... (I may have cut some corners)
This code also asssumes a 32 bit image. For 24-bit images. Change the **x\*4** to **x\*3** | This kind of thing will work but it may not be fast enough to be that useful.
```
public static Color GetDominantColor(Bitmap bmp)
{
//Used for tally
int r = 0;
int g = 0;
int b = 0;
int total = 0;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
Color clr = bmp.GetPixel(x, y);
r += clr.R;
g += clr.G;
b += clr.B;
total++;
}
}
//Calculate average
r /= total;
g /= total;
b /= total;
return Color.FromArgb(r, g, b);
}
``` | How to calculate the average rgb color values of a bitmap | [
"",
"c#",
"colors",
"rgb",
"imaging",
"channel",
""
] |
Nginx+PHP (on fastCGI) works great for me. When I enter a path to a PHP file which doesn't exist, instead of getting the default 404 error page (which comes for any invalid .html file), I simply get a "No input file specified.".
How can I customize this 404 error page? | You use the error\_page property in the nginx [config](http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page).
For example, if you intend to set the 404 error page to `/404.html`, use
```
error_page 404 /404.html;
```
Setting the 500 error page to `/500.html` is just as easy as:
```
error_page 500 /500.html;
``` | You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.
To redirect to a simple 404 not found page for a specific location:
```
location /my_blog {
error_page 404 /blog_article_not_found.html;
}
```
A site wide 404 page:
```
server {
listen 80;
error_page 404 /website_page_not_found.html;
...
```
You can append standard error codes together to have a single page for several types of errors:
```
location /my_blog {
error_page 500 502 503 504 /server_error.html
}
```
To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:
```
upstream server2 {
server 10.0.0.1:80;
}
server {
location /my_blog {
error_page 404 @try_server2;
}
location @try_server2 {
proxy_pass http://server2;
}
```
The [manual](http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page) can give you more details, or you can search google for the terms nginx.conf and error\_page for real life examples on the web. | Nginx - Customizing 404 page | [
"",
"php",
"nginx",
"http-status-code-404",
""
] |
I was wondering whether `Scala` will get the takeup it deserves without explicit corporate backing (I was thinking *by Sun/Oracle* but I suppose it could be someone else, such as *Google*).
With Sun's recent decision not to include closures in JDK7, couldn't they put their weight behind `Scala` as the Java alternative for those wishing to have a more expressive language? After all, it seems to me that they should care most about the `JVM`, not Java *per se*. Does anyone think this is likely? | You need to be more specific. Thrive in what context?
I think Scala's community is near the critical mass that it needs to be a self-sustainable open source project even if its primary institutional backer, the EPFL, suddenly had a change of heart; and there is currently every sign that it will reach this critical mass. I think Scala will be with us and actively maintained for a long time.
A more pressing issue if the type of uses for which it is suited. The Scala compiler and standard library are far from perfect. When you start pushing the language or a portion of the library there is still a decent chance that you will find bugs. This is improving by leaps and bounds, but it in itself isn't the core of the problem.
The problem is in order to get fixes you pretty much have to upgrade to the next version of Scala as upgrades come out. The problem with that is that most version upgrades contain breaking changes, thus in order to obtain fixes you are likely to have to change your own code. There's also the binary incompatibility problem, which means all your Scala dependencies have to change versions, too.
This could be severe problem if you have a lot of dependencies on other Scala libraries (unlikely - there aren't many yet), if you are subject to severe infrastructure bureaucracy, or worse, you're a product-oriented company that needs to distribute fixes to customer with severe infrastructure bureaucracy.
In order for Scala to be viable in such situations long-term, someone will have to start back porting fixes to earlier versions so that people don't have to perform breaking upgrades just to get some fixes. I'm sure this will happen, because it really wouldn't be that hard, but it will probably require someone seeing a business opportunity, because let's face it, backporting changes and doing regression testing isn't exactly exiting work. | Apart from the examples of previous languages that have succeeded without initial corporate backing, I think Microsoft's promotion of functional programming on the .NET platform may indirectly help Scala gain adoption. Since the Java and .NET ecosystems are seen as close rivals, people aware of F# and the functional additions to C# may be inclined to look for JVM analogs, and to me Scala seems best equipped to fill that role. | Can Scala survive without corporate backing? | [
"",
"java",
"scala",
"jvm-languages",
""
] |
How can I convert an Excel date (in a number format) to a proper date in Python? | You can use [xlrd](http://pypi.python.org/pypi/xlrd).
From its [documentation](https://xlrd.readthedocs.io/en/latest/index.html), you can read that dates are always stored as numbers; however, you can use [`xldate_as_tuple`](https://xlrd.readthedocs.io/en/latest/api.html#xlrd.xldate.xldate_as_tuple) to convert it to a python date.
Note: the version on the PyPI seems more up-to-date than the one available on xlrd's website. | Here's the bare-knuckle no-seat-belts use-at-own-risk version:
```
import datetime
def minimalist_xldate_as_datetime(xldate, datemode):
# datemode: 0 for 1900-based, 1 for 1904-based
return (
datetime.datetime(1899, 12, 30)
+ datetime.timedelta(days=xldate + 1462 * datemode)
)
``` | How do I read a date in Excel format in Python? | [
"",
"python",
"excel",
"datetime",
""
] |
I had a heated discussion with a colleague on the usage of stored procedures (SP) in a `.NET` application (on an SQL server 2005 database). [He has a Microsoft background and I Java - which may or may not be relevant].
I have to insert data captured in the UI. For this I would write a SP and use that in the `.NET` code? It's not required but what are the pros and cons of using a SP?
Another scenario:
I am maintaining a list of cities. User can add cities using the UI. As you expect user cannot enter a duplicate city. An error will be shown if duplicate entry happens. this can be implemented in a number of ways:
1. In my code run a select query to check if it already exists and then if not insert the city otherwise an error on UI.
2. Insert directly and due to unique index an `SQLException` will be caught. Introspect the SQLException to check what unique index is violated and show the respective error.
3. create one SP and in that handle the above logic, i.e. checking for duplicate and throw error or insert
Which one is the right way? (links to good resources are welcome). | Firstly, it is a good idea to use SPs, rather than adhoc SQL statements because:
1) security - only need to grant permission to execute the sproc, NOT on the underlying tables
2) maintainability - can patch the SP within SQL Server without having to rebuild/deploy .NET code in order to tweak a query
3) performance - execution plan caching/reuse when using sprocs improves performance (can be done also if using parameterised SQL direct within your .NET)
4) network traffic (ok, negligible but SPs save you passing the whole SQL statement across the network, particularly if large query)
Exceptions are expensive, so try to avoid exceptions being thrown when you can prevent it.
I'd recommend writing a sproc that does an IF EXISTS check prior to trying to INSERT a record and only inserting if it doesn't exist. Just return out a return code or output parameter indicating what happened. e.g. 0=inserted OK, -1=already exists
Do it all within the one sproc call to save DB round trips (i.e. don't query the db first to check, and then send another statement in to do the INSERT). Using an EXISTS check is the most optimal way of checking. | As a general rule of thumb, if the application is the only user of a given database schema, then I would advise using direct SQL (i.e. no SPs). If the database is shared between applications, it becomes much more critical to control the interface between applications and shared data, and the easiest way to define this interface is to control access to the data via stored procedures.
The use of SPs adds to the complexity of the system, and you shouldn't add complexity unless there's a good reason for it. It can also severely hamper your application's use of good ORM tools.
But as with all rules of thumb, there are always exceptions. | Stored procedure for everything | [
"",
"java",
".net",
"stored-procedures",
""
] |
Greetings,
I have a form where employees enter comments in a multiline textbox with a limit of 4000 characters. I have the rows set to 8 (obviously an arbitrary number).
When a supervisor looks at the comments the textbox is disabled so the employee comments cannot be modified.
The problem is when the data extends below row 8. Since the textbox is disabled the scrollbar cannot be moved and the supervisor cannot see all the comments. If I hide the textbox and databind to a label for the supervisor none of the line breaks are maintained and a well written paragraph turns into the biggest run on sentence ever…
Is there a way to enable the scroll bar leaving the text disabled?
Is there a way to preserve the structure of the entry in the label? | In supervisor mode, don't put the text into a textbox, put it in a label as you mentioned, with '.Replace("\n", "<br>")' in your code.
Alternatively, show the textbox without disabling it, and just disable the 'save' button. Put a note on the page saying that, "changes made here are not persistent" or something to that effect. | Instead of disabling the textbox you should set the [ReadOnly property](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.readonly.aspx) to True. This keeps the scrollbars functional but doesn't allow modification of the textbox.
```
txtComments.ReadOnly = true;
``` | ASP.net textbox scrolling when disabled | [
"",
"c#",
"asp.net",
"asp.net-3.5",
""
] |
I want to make sure I'm not inserting a duplicate row into my table (e.g. only primary key different). All my fields allow NULLS as I've decided null to mean "all values". Because of nulls, the following statement in my stored procedure can't work:
```
IF EXISTS(SELECT * FROM MY_TABLE WHERE
MY_FIELD1 = @IN_MY_FIELD1 AND
MY_FIELD2 = @IN_MY_FIELD2 AND
MY_FIELD3 = @IN_MY_FIELD3 AND
MY_FIELD4 = @IN_MY_FIELD4 AND
MY_FIELD5 = @IN_MY_FIELD5 AND
MY_FIELD6 = @IN_MY_FIELD6)
BEGIN
goto on_duplicate
END
```
since NULL = NULL is not true.
How can I check for the duplicates without having an IF IS NULL statement for every column? | Use [`INTERSECT`](http://msdn.microsoft.com/en-us/library/ms188055.aspx) operator.
It's `NULL`-sensitive and efficient if you have a composite index on all your fields:
```
IF EXISTS
(
SELECT MY_FIELD1, MY_FIELD2, MY_FIELD3, MY_FIELD4, MY_FIELD5, MY_FIELD6
FROM MY_TABLE
INTERSECT
SELECT @IN_MY_FIELD1, @IN_MY_FIELD2, @IN_MY_FIELD3, @IN_MY_FIELD4, @IN_MY_FIELD5, @IN_MY_FIELD6
)
BEGIN
goto on_duplicate
END
```
Note that if you create a `UNIQUE` index on your fields, your life will be much simpler. | Along the same lines as [@Eric's answer](https://stackoverflow.com/questions/1075142/how-to-compare-values-which-may-both-be-null-is-t-sql#answer-1075150), but without using a `'NULL'` symbol.
```
(Field1 = Field2) OR (ISNULL(Field1, Field2) IS NULL)
```
This will be true only if both values are `non-NULL`, and equal each other, or both values are `NULL` | How to compare values which may both be null in T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
Unlike std::map and std::hash\_map, corresponding versions in Qt do not bother to return a reference. Isn't it quite inefficient, if I build a hash for quite bulky class?
**EDIT**
especially since there is a separate method value(), which could then return it by value. | const subscript operators of `STL` containers can return a reference-to-const because they flat out deny calls to it with indexes that do not exist in the container. Behaviour in this case is undefined. Consequently, as a wise design choice, `std::map` doesn't even provide a const subscript operator overload.
QMap tries to be a bit more accommodating, provides a const subscript operator overload as syntactic sugar, runs into the problem with non-existing keys, again tries to be more accomodating, and returns a default-constructed value instead.
If you wanted to keep STL's return-by-const-reference convention, you'd need to allocate a static value and return a reference to *that*. That, however, would be quite at odds with the reentrancy guarantees that `QMap` provides, so the only option is to return by value. The `const` there is just sugar coating to prevent some stupid mistakes like `constmap["foo"]++` from compiling.
That said, returning by reference is not always the most efficient way. If you return a fundamental type, or, with more aggressive optimisation, when `sizeof(T)<=sizeof(void*)`, return-by-value often makes the compiler return the result in a register directly instead of indirectly (address to result in register) or—heaven forbid—on the stack.
The other reason (besides premature pessimisation) to prefer pass-by-const-reference, slicing, doesn't apply here, since both `std::map` and `QMap` are value-based, and therefore homogeneous. For a heterogeneous container, you'd need to hold pointers, and pointers are fundamental types (except smart ones, of course).
That all said, I almost never use the const subscript operator in Qt. Yes, it has nicer syntax than `find()`+`*it`, but invariably, you'll end up with `count()`/`contains()` calls right in front of the const subscript operator, which means you're doing the binary search *twice*. And *then* you won't notice the miniscule differences in return value performance anyway :)
For `value() const`, though, I agree that it should return reference-to-const, defaulting to the reference-to-default-value being passed in as second argument, but I guess the Qt developers felt that was too much magic. | The documentation for QMap and QHash specifically say to avoid `operator[]` for lookup due to the reason Martin B stated.
If you want a const reference, use `const_iterator find ( const Key & key ) const` where you can then use any of:
```
const Key & key () const
const T & value () const
const T & operator* () const
const T * operator-> () const
``` | Any ideas why QHash and QMap return const T instead of const T&? | [
"",
"c++",
"qt",
"hash",
"reference",
"performance",
""
] |
I have a test winforms app with ThreadExceptionHandler that displays a message box when an unhandled exception is caught, as follows:
```
[STAThread]
static void Main()
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show("error caught");
}
```
When I force an error in the ctor of Form 1 (e.g. dividebyzero) as follows:
```
public Form1()
{
InitializeComponent();
int i = 0;
int x = 5 / i;
}
```
and run the app outside of Visual Studio (in Windows 7), the divide by zero exception is *not* handled - I get an unhelpful "WindowsFormApplication1 has stopped working..." message.
*However*, when I move the dividebyzero exception to the Form1\_Load event and rerun, the exception is handled properly.
Can someone explain why this is the case? The reason I ran this test program is because I am experiencing a similar unhandled exception issue in another, enterprise app that I am trying to track down. | This is probably due to the fact that the constructor is executed before `Application.Run()` is called. Your code could also be written as
```
[STAThread]
static void Main()
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 MyForm = new Form1();
Application.Run(MyForm);
}
```
Your thread exception handler only becomes active when `Application.Run()` is executing. In order to catch exceptions in the form constructor, you need to surround `Form1 MyForm = new Form1();` witch a seperate try/catch block. | The error is being thrown in the **constructor**, not in the threaded code. Your code:
```
Application.Run(new Form1());
```
is going to throw the exception right then and there, on that very line of code, before the call to `Application.Run()`, so the threaded code doesn't even begin executing. | ThreadExceptionHandler not catching exception in MainFrm constructor | [
"",
"c#",
"exception",
""
] |
I have a web archive with a file placed in the WEB-INF directory.
How do I load that file in a java class?
I know I can put it in the classes directory and load it from there. It would just be put it in WEB-INF. | Use the `getResourceAsStream()` method on the ServletContext object, e.g.
```
servletContext.getResourceAsStream("/WEB-INF/myfile");
```
How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?
EDITED: If you're inside a Servlet object, then call `getServletContext()`. If you're in JSP, use the predefined variable `application`. | Here is how it works for me with no Servlet use.
Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml
1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )
2. Now let's use class loader:
```
InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
``` | How to load a resource from WEB-INF directory of a web archive | [
"",
"java",
""
] |
I'm using the [jQuery Fancybox plugin](http://fancy.klade.lv/) to create a modal window with the link's `href` as the content, and the `title` as its caption. I'd like to be able to have a clickable link in the caption (in this case to lead to a larger map) but I can't put an `<a>` tag into the `title` attribute. How might I go about putting this link in through Javascript, jQuery, or other methods?
```
<a class='iframe' href='http://maps.google.com/maps?q=%235+Health+Department+Drive,+Troy,+MO+63379&ll=38.979228,-90.97847&z=13&iwloc=near&num=1&output=embed' title='Google Map to Lincoln County Health Department'>Map to LCHD</a>
```
[](https://i.stack.imgur.com/4BBJg.png) | I'm not familiar with this plugin, but this method comes to mind.
You can bury content elements within the anchor and modify you plugin to use the elements that your introduce. For example:
```
<a class='iframe'
href='http://maps.google.com/blahlblahlbah'
title='Google Map to Lincoln County Health Department'>Map to LCHD
<span class="title-href" style="display: none">http://zebrakick.com</span>
</a>
```
Hope that helps. | Keep the element => destination\_link map as an object, and fetch values from it for redirection.
```
var linkmap = {
lincoln: '/location/3/',
someplace: '/location/99'
}
```
Now you can use the values from linkmap in your click event (with [] or . operator) | Can I put a link inside a title attribute? | [
"",
"javascript",
"jquery",
"html",
"fancybox",
""
] |
Does anyone know a quick and dirty threadsafe vector class for c++? I am multithreading some code, and I believe the problem I have is related to the way the vectors are used. I plan to rewrite the code, but before I go crazy redoing the code, I would like to test it with a threadsafe vector to be sure. I also figure if such a thing is out there, it would be much easier than writing my own version. | This is difficult because of algorithms.
Suppose you wrapped vector so that all its member functions are serialised using a mutex, like Java synchronized methods. Then concurrent calls to `std::remove` on that vector still wouldn't be safe, because they rely on looking at the vector and changing it based on what they see.
So your LockingVector would need to specialize every template in the standard algorithms, to lock around the whole thing. But then other algorithms like `std::remove_if` would be calling user-defined code under the lock. Doing this silently behind the scenes is a recipe for locking inversion as soon as someone starts creating vectors of objects which themselves internally take locks around all their methods.
In answer to your actual question: sorry, no, I don't know of one. For a quick test of the kind you need, I recommend that you start out with:
```
template <typename T>
class LockedVector {
private:
SomeKindOfLock lock;
std::vector<T> vec;
};
```
Then drop it in as a replacement container, and start implementing member functions (and member typedefs, and operators) until it compiles. You'll notice pretty quickly if any of your code is using iterators on the vector in a way which simply cannot be made thread-safe from the inside out, and if need be you can temporarily change the calling code in those cases to lock the vector via public methods. | You can check out [TBB](http://www.threadingbuildingblocks.org/codesamples.php) (like [concurrent\_vector](http://www.threadingbuildingblocks.org/codesamples.php#concurrent_vector)). I've never used it though, honestly, I find putting the scope guard objects around access easier (especially if the vector is properly encapsulated). | Threadsafe Vector class for C++ | [
"",
"c++",
"multithreading",
"thread-safety",
""
] |
[**This question about Timers for windows services**](https://stackoverflow.com/questions/246697/windows-service-and-timer) got me thinking:
Say I have (and I do) a windows service thats waiting on a [WaitHandle](http://www.albahari.com/threading/part2.aspx#_Wait_Handles) and when woken, it dives into a wait-spin like I have shown below in a flowchart
[wait spin diagram http://www.86th.org/waitspin.jpg](http://www.86th.org/waitspin.jpg)
I'm curious if using a timer would be better than a [wait-spin loop](http://www.albahari.com/threading/part2.aspx#_Synchronization_Essentials) (sometimes called a spin-wait). I'll be honest, I've never used timers for anything other than my own tinkering.
I don't have any plans to switch unless the differences are profound and the benefits of using a Timer are amazing. However, I'm very interested on peoples thoughts on one vs the other for future development of this project.
Let me know if this should be a wiki | I don't see you getting any benefit out of a timer. You are essentially behaving as a timer anyway with your sleep call, and you are not being a bandwidth hog since sleep yields up the time slice. Having an explicit timer wake up and call you is just going to complicate the code.
I wouldn't really say that you are doing a spin-wait, since I generally think of a spin-wait as something that doesn't sleep. It just burns all it's processor time waiting for the go signal. | Sleeping a thread and waiting on a handle with a timeout are basically the same thing under the covers. I would guess that timers are essentially implemented using sleep, so not much difference there, either. In other words, you could simplify your code by waiting on the handle with a timeout in a single loop and checking to see why the wait was released (data available or timeout), rather than implementing separate wait and sleep loops. Slightly more efficient than independent loops.
Ideally, you would not use sleep at all and simply depend on the data-generation code to correctly raise the event your consumption code is waiting on, with a longish timeout to handle when the event source has gone away.
If the data is external, such as on a socket or other input device, then the handle can generally be set to allow waiting for data to become available - no need to poll in that case since the event will always be signaled when data is ready for consumption. | For a windows service, which is better, a wait-spin or a timer? | [
"",
"c#",
".net",
"sleep",
"waithandle",
""
] |
I use data binding to display values in text boxes in a C# Windows Forms client. When the user clicks Save, I persist my changes to the database. However, the new value in the active editor is ignored (the previous value is saved). If I tab out of the active editor, and then Save, the new value is persisted, as expected.
Is there a way to force the active control to accept its value before persisting? | If you can get the [`Binding`](http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.aspx) instance that corresponds to the input (the [`TextBox`](http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.aspx)), you can call the [`WriteValue` method](http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.writevalue.aspx) to force the value from the control to the object it is bound to.
Also, you can call the [`EndCurrentEdit` method](http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingmanagerbase.endcurrentedit.aspx) on the [`BindingManagerBase` class](http://msdn.microsoft.com/en-us/library/7he0a7s1) (usually a [`CurrencyManager` class](http://msdn.microsoft.com/en-us/library/system.windows.forms.currencymanager.aspx) instance) to finish the edit, but that requires implementation of the [`ICancelAddNew`](http://msdn.microsoft.com/en-us/library/system.componentmodel.icanceladdnew.aspx) or [`IEditableObject`](http://msdn.microsoft.com/en-us/library/system.componentmodel.ieditableobject.aspx) interface on the object that is bound to (and wouldn't require you to fish for the binding). | The solution I've used is to call `ValidateChildren` on the Form from the Save event (call), before actually saving the database records. This forces validation of all fields and thus binding to occur without losing focus of the control currently being edited on the form. It is real handy if the save button is on the Windows menu system and not form itself - plus it returns False if data in any control on the form is invalid and thus can be used to prevent saving errant data.
This also gets around inconsistent updating of the bound field that occurs when `OnPropertyChanged` is used as a binding method instead of `OnValidation`. Also, it is critical if the binding method is set to Never with separate WriteValue calls made for each validated event trapped per control. | Databound Windows Forms control does not recognize change until losing focus | [
"",
"c#",
"winforms",
"data-binding",
""
] |
I'm trying to allow my php pages to run inside a content page of the master page. I'd like to run php somehow inside a master page. Besides frames is there another way? I've read you can use a frame, but would prefer not to. If I have to go with frames to get it done, should I be using an asp.net frame class of some sort or the raw html type? | Well, there's always [Phalanger](http://www.codeplex.com/Wiki/View.aspx?ProjectName=Phalanger) for running PHP within the .NET framework, but I recommend against mixing environments like that.
If your PHP pages live on a different server, frame them. If you *must* have them on the same server, Phalanger them.
In both cases, I suggest you take a good, long, hard look at what you're doing and try to find another way. | First, this is a really bad idea.
Second, if you really want to compound the bad idea, use frames or iframes. Of course, I hope you don't have Safari clients.
**UPDATE:**
Okay, I can think of ONE way. Do an http request for the php page during execution of your ASPX page. Filter out everything you don't need and inject the rest.
However, I still stand by my statement about this being a bad idea and believe you are better off throwing the PHP stuff away. The reason being that the next step in your quest will be to post data back from the php to the .net app; then it really starts going downhill. | can I get php to run in an asp.net page? | [
"",
".net",
"php",
"asp.net",
"master-pages",
""
] |
Currently we have thousands of Microsoft Word files, Excel files, PDF's, images etc stored in folders/sub folders. These are generated by an application on a regular basis and can be accessed at any time within that application. As we look to upgrade we are now looking into storing all these documents within SQL Server 2005 instead. Reasons for this are based on being able to compress the documents, adding additional fields to store more information on those documents and applying index’s where necessary.
I suppose what I’m after is the pros and cons of using SQL Server as a document repository instead of keeping them on the file server, as well as any experience you might have in doing this.
We would be using C# and Windows Workflow to do this task.
Thanks for your comments.
Edit
---
How big are the files?
**between 100k = 200k in size (avg. 70KB)**
How many will be?
**At the moment it’s around 3.1 Million files (ranging from Word/Excel and PDF's), which can grow by 2,600 a day. (The growth will also increase over time)**
How many reads?
**This one is difficult to quantify as our old system/application makes it hard to work this out.**
---
Also another useful link pointed out on a similar post covers the pros and cons of both methods.
[Files Stored on DB vs FileSystem - Pros and Cons](https://stackoverflow.com/questions/616762/what-is-the-best-way-to-associate-a-file-with-a-piece-of-data) | I would have both.
I would keep the files renamed with an unique name, thus easier to manage, and i would keep all meta data inside the database (file name, content-type, location on file system, size, description, etcetera), so the files are accessed through the database (indirectly).
Advantages:
* files are easy to handle; you can bring several drives in the mix
* the database can keep any number of meta information, including file description on which you can search against.
* keep track on file accesses and other statistic information
* rearrange the files using various paradigms: tree (directory structure), tags, search or context
You can have compression on a drive also. You can have RAID for backup and speed. | rule of thumb for doc size is:
```
size < 256 kb: store in db
265 kb < size < 1 MB: test for your load
size > 1 Mb: store on file system
```
EDIT: this rule of thumb also applies for FILESTREAM storage in SQL Server 2008 | Store Files in SQL Server or keep them on the File Server? | [
"",
"c#",
"sql-server",
"sql-server-2005",
"workflow-foundation",
""
] |
I was trying to write up a class in c++, and I came across a rather odd problem: calling outside functions inside of a class that have the same name as the class. It's kinda confusing, so here's an example:
```
void A(char* D) {
printf(D);
}
class A
{
public:
A(int B);
void C();
};
A::A(int B) {
// something here
}
void A::C() {
A("Hello, World.");
}
```
The compiler complains at the second to last line that it can't find a function A(char\*), because it is inside the class, and the constructor has the same name as the function. I could write another function outside, like:
```
ousideA(char* D) {
A(D);
}
```
And then call outsideA inside of A::C, but this seems like a silly solution to the problem. Anyone know of a more proper way to solve this? | ```
::A("Hello, world.");
```
should work fine. Basically it is saying "use the `A` found in the global namespace" | Use the [scope resolution operator](http://en.wikipedia.org/wiki/Scope_resolution_operator) `::` to access the name from the global scope:
```
void A::C() {
::A("Hello, world.");
}
``` | C++ - Calling a function inside a class with the same name as the class | [
"",
"c++",
"class",
"constructor",
""
] |
I got myself in a situation where using the System.Attribute class seemed (at first glance) to be a good idea.
I have an object to be printed in my application, and I need a label before each property (or just a string before it). I could put each property hardcoded like:
```
Console.WriteLine("Color:"+obj.color);
Console.WriteLine("Size:"+obj.size);
```
And so on for each property. But instead of it, I was trying to create a code where this 'label' doesn't needed to be hardcoded, so I could print every property dynamically.
I got something like that, using System.Attribute class:
```
public class MyObject
{
[MyCustomLabel("Color:")]
public string Color;
[MyCustomLabel("Size:")]
public string Size;
//etc...
}
```
So here comes my problem: retrieving this Attribute's value is not impossible, but it's not friendly since I had to use some reflection for it.
I'm not really scared of using reflection, but it seemed that I was using attributes for something that it wasn't created for.
I wonder where are the best places for using attributes, and if this is really a situation for using it. | Attributes and reflection go hand in hand. With the exception of some compiler/runtime attributes, there's no way to use them with out reflecting over the code.
That said, your approach is reasonable, and you might want to take a look at the attributes in the `System.ComponentModel` namespace which have a number of classes to decorate properties with useful metadata. | If you're just writing to the console, i.e. it's debugging style output then what you want is minimal chance of typo/copy paste error.
This is confusing under the hood but is highly effective at the call sites:
```
public static void WriteNameAndValue<T,TValue>(
this TextWriter tw, T t,
Expression<Func<T, TValue>> getter)
{
var memberExpression = getter.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("missing body!");
var member = memberExpression.Member;
tw.Write(member.Name);
tw.Write(": ");
if (member is FieldInfo)
{
tw.Write(((FieldInfo)member).GetValue(t));
}
else if (member is PropertyInfo)
{
tw.Write(((PropertyInfo)member).GetValue(t, null));
}
}
public static void WriteNameAndValueLine<T,TValue>(
this TextWriter tw, T t,
Expression<Func<T, TValue>> getter)
{
WriteNameAndValue<T,TValue>(tw, t, getter);
tw.WriteLine();
}
```
then you can write
```
t.Foo = "bar";
t.Bar = 32.5;
Console.Out.WriteNameAndValueLine(t, x => x.Foo);
Console.Out.WriteNameAndValueLine(t, x => x.Bar);
// output
// Foo: bar
// Bar: 32.5
```
If you want this to be more configurable at runtime via resources and with considerations for localization you can do so but I would consider another, more standardized, approach instead if this was a likely requirement.
P.S. if you wanted to get fancy you could replace the FieldInfo/PropertyInfo switch with
```
tw.Write(getter.Compile()(t));
```
and then you could check for MethodInfo in the expression as well (or allow arbitrary lambdas and just insert the line number or some other generic text. I suggest not going down this route, the usage is already confusing also this may cause unwanted load in what should be a simple logging method. | Using System.Attribute class | [
"",
"c#",
"reflection",
"code-reuse",
""
] |
I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.
Are there performance or other disadvantages to saving the values as strings? | Unless you really need the features of an integer (that is, the ability to do arithmetic), then it is probably better for you to store the product IDs as strings. You will never need to do anything like add two product IDs together, or compute the average of a group of product IDs, so there is no need for an actual numeric type.
It is unlikely that storing product IDs as strings will cause a measurable difference in performance. While there will be a slight increase in storage size, the size of a product ID string is likely to be much smaller than the data in the rest of your database row anyway.
Storing product IDs as strings today will save you much pain in the future if the data provider decides to start using alphabetic or symbol characters. There is no real downside. | Do NOT consider performance. Consider meaning.
ID "numbers" are not numeric except that they are written with an alphabet of all digits.
If I have part number 12 and part number 14, what is the difference between the two? Is part number 2 or -2 meaningful? No.
Part numbers (and anything that doesn't have units of measure) are not "numeric". They're just strings of digits.
Zip codes in the US, for example. Phone numbers. Social security numbers. These are not numbers. In my town the difference between zip code 12345 and 12309 isn't the distance from my house to downtown.
Do not conflate numbers -- with units -- where sums and differences *mean* something with strings of digits without sums or differences.
Part ID numbers are -- properly -- strings. Not integers. They'll never be integers because they don't have sums, differences or averages. | Drawbacks of storing an integer as a string in a database | [
"",
"python",
"mysql",
"database",
"database-design",
""
] |
OK, so I know that `from-import` is "exactly" the same as `import`, except that it's obviously not because namespaces are populated differently.
My question is primarily motivated because I have a `utils` module which has one or two functions that are used by every other module in my app, and I'm working on incorporating the standard library `logging` module, which as far as I can tell I need to do sorta like this:
```
import logging
logging.basicConfig(filename="/var/log") # I want file logging
baselogger = logging.getLogger("mine")
#do some customizations to baselogger
```
and then to use it in a different module I would import logging again:
```
import logging
logger = logging.getlogger("mine")
# log stuff
```
But what I want to know is if I do a `from utils import awesome_func` will my logger definitely be set up, and will the logging module be set up the way I want?
This would apply to other generic set-ups as well. | Looks like like the answer is yes:
```
$ echo 'print "test"
def f1():
print "f1"
def f2():
print "f2"
' > util.py
$ echo 'from util import f1
f1()
from util import f2
f2()
' > test.py
$ python test.py
test
f1
f2
$
``` | The answer to your question is yes.
For a good explanation of the import process, please see Frederik Lundh's "[Importing Python Modules](http://effbot.org/zone/import-confusion.htm)".
In particular, I'll quote the sections that answer your query.
> **What Does Python Do to Import a Module?**
>
> [...]
>
> 1. Create a new, empty module object (this is essentially a dictionary)
> 2. Insert that module object in the sys.modules dictionary
> 3. Load the module code object (if necessary, compile the module first)
> 4. Execute the module code object in the new module’s namespace. All variables assigned by the code will be available via the module object.
and on the use of `from-import`:
> **There are Many Ways to Import a Module**
>
> [...]
>
> **from X import a, b, c** imports the module X, and creates references in the current namespace to the given objects. Or in other words, you can now use a and b and c in your program.
Note I've elided some matter. It's worth reading the entire document, it's actually quite short. | Does "from-import" exec the whole module? | [
"",
"python",
"logging",
"import",
""
] |
I have some tables that benefit from many-to-many tables. For example the team table.
Team member can hold more than one 'position' in the team, all the positions are listed in the position db table. The previous positions held are also stored for this I have a separate table, so I have
* member table (containing team details)
* positions table (containing positions)
* member\_to\_positions table (id of member and id of position)
* member\_to\_previous\_positions (id of member and id of position)
Simple, however the crux comes now that a team member can belong to many teams aghhh.
I already have a team\_to\_member look-up table.
Now the problem comes how do I tie a position to a team? A member may have been team leader on one team, and is currently team radio man and press officer on a different team. How do I just pull the info per member to show his current position, but also his past history including past teams.
Do I need to add a position\_to team table and somehow cross reference that, or can I add the team to the member to positions table?
It's all very confusing, this normalization. | It's perfectly legitimate to have a TeamPositionMember table, with the columns
```
Team_Id
Position_Code
Member_Id
Start_Date
End_Date NULLABLE
```
And and a surrogate ID column for Primary Key if you want; otherwise it's a 3-field composite Primary Key. (You'll want a uniqueness constraint on this anyway.)
With this arrangement, you can have a team with any set of positions. A team can have zero or more persons per position. A person can fill zero or more positions for zero or more teams.
EDIT:
If you want dates, just revise as shown above, and add Start\_Date to the PK to allow the same person to hold the same position at different times. | Yes, a many-to-many junction table can have additional attributes (columns).
For example, if there's a table called PassengerFlight table that's keyed by PassengerID and FlightID, there could be a third column showing the status of the given passenger on the given flight. Two different statuses might be "confirmed" and "wait listed", each of them coded somehow.
In addition, there can be ternary relationships, relationships that involve three entities and not just two. These tables are going to have three foreign keys that taken together are the primary key for the relationship table. | Can a many-to-many join table have more than two columns? | [
"",
"sql",
"mysql",
"database-design",
"join",
"many-to-many",
""
] |
Hey everyone, great community you got here. I'm an Electrical Engineer doing some "programming" work on the side to help pay for bills. I say this because I want you to take into consideration that I don't have proper Computer Science training, but I have been coding for the past 7 years.
I have several excel tables with information (all numeric), basically it is "dialed phone numbers" in one column and number of minutes to each of those numbers on another. Separately I have a list of "carrier prefix code numbers" for the different carriers in my country. What I want to do is separate all the "traffic" per carrier. Here is the scenario:
**First dialed number row**: *123456789ABCD,100* <-- That would be a 13 digit phone number and 100 minutes.
I have a list of 12,000+ prefix codes for carrier 1, these codes vary in length, and I need to check everyone of them:
**Prefix Code 1**: *1234567* <-- this code is 7 digits long.
I need to check the first 7 digits for the dialed number an compare it to the dialed number, if a match is found, I would add the number of minutes to a subtotal for later use. ***Please consider that not all prefix codes are the same length, some times they are shorter or longer.***
Most of this should be a piece of cake, and I could should be able to do it, but I'm getting kind of scared with the massive amount of data; Some times the dialed number lists consists of up to 30,000 numbers, and the "carrier prefix code" lists around 13,000 rows long, and I usually check 3 carriers, that means I have to do a lot of "matches".
Does anyone have an idea of how to do this efficiently using C#? Or any other language to be kind honest. I need to do this quite often and designing a tool to do it would make much more sense. I need a good perspective from someone that does have that "Computer Scientist" background.
Lists don't need to be in excel worksheets, I can export to csv file and work from there, I don't need an "MS Office" interface.
Thanks for your help.
Update:
Thank you all for your time on answering my question. I guess in my ignorance I over exaggerated the word "efficient". I don't perform this task every few seconds. It's something I have to do once per day and I hate to do with with Excel and VLOOKUPs, etc.
I've learned about new concepts from you guys and I hope I can build a solution(s) using your ideas. | **UPDATE**
You can do a simple trick - group the prefixes by their first digits into a dictionary and match the numbers only against the correct subset. I tested it with the following two LINQ statements assuming every prefix has at least three digis.
```
const Int32 minimumPrefixLength = 3;
var groupedPefixes = prefixes
.GroupBy(p => p.Substring(0, minimumPrefixLength))
.ToDictionary(g => g.Key, g => g);
var numberPrefixes = numbers
.Select(n => groupedPefixes[n.Substring(0, minimumPrefixLength)]
.First(n.StartsWith))
.ToList();
```
So how fast is this? **15.000 prefixes and 50.000 numbers took less than 250 milliseconds.** Fast enough for two lines of code?
Note that the performance heavily depends on the minimum prefix length (MPL), hence on the number of prefix groups you can construct.
```
MPL Runtime
-----------------
1 10.198 ms
2 1.179 ms
3 205 ms
4 130 ms
5 107 ms
```
Just to give an rough idea - I did just one run and have a lot of other stuff going on.
**Original answer**
I wouldn't care much about performance - an average desktop pc can quiete easily deal with database tables with 100 million rows. Maybe it takes five minutes but I assume you don't want to perform the task every other second.
I just made a test. I generated a list with 15.000 unique prefixes with 5 to 10 digits. From this prefixes I generated 50.000 numbers with a prefix and additional 5 to 10 digits.
```
List<String> prefixes = GeneratePrefixes();
List<String> numbers = GenerateNumbers(prefixes);
```
Then I used the following LINQ to Object query to find the prefix of each number.
```
var numberPrefixes = numbers.Select(n => prefixes.First(n.StartsWith)).ToList();
```
Well, it took about a minute on my Core 2 Duo laptop with 2.0 GHz. So if one minute processing time is acceptable, maybe two or three if you include aggregation, I would not try to optimize anything. Of course, it would be realy nice if the programm could do the task in a second or two, but this will add quite a bit of complexity and many things to get wrong. And it takes time to design, write, and test. The LINQ statement took my only seconds.
**Test application**
Note that generating many prefixes is really slow and might take a minute or two.
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace Test
{
static class Program
{
static void Main()
{
// Set number of prefixes and calls to not more than 50 to get results
// printed to the console.
Console.Write("Generating prefixes");
List<String> prefixes = Program.GeneratePrefixes(5, 10, 15);
Console.WriteLine();
Console.Write("Generating calls");
List<Call> calls = Program.GenerateCalls(prefixes, 5, 10, 50);
Console.WriteLine();
Console.WriteLine("Processing started.");
Stopwatch stopwatch = new Stopwatch();
const Int32 minimumPrefixLength = 5;
stopwatch.Start();
var groupedPefixes = prefixes
.GroupBy(p => p.Substring(0, minimumPrefixLength))
.ToDictionary(g => g.Key, g => g);
var result = calls
.GroupBy(c => groupedPefixes[c.Number.Substring(0, minimumPrefixLength)]
.First(c.Number.StartsWith))
.Select(g => new Call(g.Key, g.Sum(i => i.Duration)))
.ToList();
stopwatch.Stop();
Console.WriteLine("Processing finished.");
Console.WriteLine(stopwatch.Elapsed);
if ((prefixes.Count <= 50) && (calls.Count <= 50))
{
Console.WriteLine("Prefixes");
foreach (String prefix in prefixes.OrderBy(p => p))
{
Console.WriteLine(String.Format(" prefix={0}", prefix));
}
Console.WriteLine("Calls");
foreach (Call call in calls.OrderBy(c => c.Number).ThenBy(c => c.Duration))
{
Console.WriteLine(String.Format(" number={0} duration={1}", call.Number, call.Duration));
}
Console.WriteLine("Result");
foreach (Call call in result.OrderBy(c => c.Number))
{
Console.WriteLine(String.Format(" prefix={0} accumulated duration={1}", call.Number, call.Duration));
}
}
Console.ReadLine();
}
private static List<String> GeneratePrefixes(Int32 minimumLength, Int32 maximumLength, Int32 count)
{
Random random = new Random();
List<String> prefixes = new List<String>(count);
StringBuilder stringBuilder = new StringBuilder(maximumLength);
while (prefixes.Count < count)
{
stringBuilder.Length = 0;
for (int i = 0; i < random.Next(minimumLength, maximumLength + 1); i++)
{
stringBuilder.Append(random.Next(10));
}
String prefix = stringBuilder.ToString();
if (prefixes.Count % 1000 == 0)
{
Console.Write(".");
}
if (prefixes.All(p => !p.StartsWith(prefix) && !prefix.StartsWith(p)))
{
prefixes.Add(stringBuilder.ToString());
}
}
return prefixes;
}
private static List<Call> GenerateCalls(List<String> prefixes, Int32 minimumLength, Int32 maximumLength, Int32 count)
{
Random random = new Random();
List<Call> calls = new List<Call>(count);
StringBuilder stringBuilder = new StringBuilder();
while (calls.Count < count)
{
stringBuilder.Length = 0;
stringBuilder.Append(prefixes[random.Next(prefixes.Count)]);
for (int i = 0; i < random.Next(minimumLength, maximumLength + 1); i++)
{
stringBuilder.Append(random.Next(10));
}
if (calls.Count % 1000 == 0)
{
Console.Write(".");
}
calls.Add(new Call(stringBuilder.ToString(), random.Next(1000)));
}
return calls;
}
private class Call
{
public Call (String number, Decimal duration)
{
this.Number = number;
this.Duration = duration;
}
public String Number { get; private set; }
public Decimal Duration { get; private set; }
}
}
}
``` | It sounds to me like you need to build a [trie](http://en.wikipedia.org/wiki/Trie) from the carrier prefixes. You'll end up with a single trie, where the terminating nodes tell you the carrier for that prefix.
Then create a dictionary from carrier to an `int` or `long` (the total).
Then for each dialed number row, just work your way down the trie until you find the carrier. Find the total number of minutes so far for the carrier, and add the current row - then move on. | Comparing 2 huge lists using C# multiple times (with a twist) | [
"",
"c#",
"list",
"compare",
"matching",
""
] |
I have a read only combo-box with 5 values in, when the user selects a new value what event should I use to write that value to the registry?
Thanks | Well regardless of what you will end up doing with the value when selected, it is safe to use the `SelectionChangeCommitted` event.
Here is a little follow up info on this event vs the other commonly used events. (from MSDN)
> SelectionChangeCommitted is raised
> only when the user changes the combo
> box selection. Do not use
> SelectedIndexChanged or
> SelectedValueChanged to capture user
> changes, because those events are also
> raised when the selection changes
> programmatically. | I usually use the `SelectedIndexChanged` event to check when a user selects a value in a combobox | C# Combo box value change, what Event should I use to write update the registry? | [
"",
"c#",
"combobox",
""
] |
While user uploading a file, is it possible to know if the uploaded file is an image or not,
I am open for any solution, Client Side, Server Side or both and we choose based on the case. | Yes, by checking the [magic number](http://en.wikipedia.org/wiki/Magic_number_(programming)) of the file. | May be you can use following code to check if the file is an image.
```
public bool IsFileAnImage(string filePath)
{
try
{
Image image = Image.FromFile(filePath))
}
catch
{
return false;
}
finally
{
image.Dispose();
}
return true;
}
``` | Is it possible to know if the type of the uploaded file is an image? | [
"",
"asp.net",
"javascript",
"image",
"file-upload",
""
] |
When I develop a C# console application (which will run on a server) and I run it using Visual Studio, I get a "Press any key to continue" message before the program terminates.
However, when I compile the very same C# code file manually using CSC, my program doesn't show that message and it terminates immediately after finishing its logic.
Does anyone know how I can make the same feature when compiling the code without using VS and WITHOUT changing the C# code any adding a ReadLine()?
**UPDATE : The same message used to appear when I learned C#, I used to use TextPad with CSC, and that message used to appear without adding any Write(Line)/Read(Line) callings** | You could write a batch script that runs the exe for you and prompts the user to press a key.
The batch script would look something like this:
```
echo off
YourApp.exe
pause
``` | It's nothing to do with the compiler - if you press `F5` to debug it rather than `Ctrl-F5` to run without debugging, then VS doesn't show the prompt. This is presumably so that you don't miss whatever output it's producing.
In order to do this, Visual Studio runs cmd.exe telling it to run your executable and then pause:
```
"C:\WINDOWS\system32\cmd.exe" /c ""...\ConsoleApplication1.exe" & pause"
```
It probably doesn't do it when you debug as it's a bit harder to get the process ID of a child of a child process.
To add a similar option to your program, either use a command line switch to tell the application itself to pause, or use a batch file to run it then pause, or use a shortcut with them `cmd.exe /c`. | How does VS compile console applications to show "Press any key to continue"? | [
"",
"c#",
".net",
"visual-studio",
"console",
""
] |
I have a script which hides (display:none) certain divs in the list on page load. Div contents represents description of a book, and the whole list is some sort of bibliography. Every div has an id, for example, "div1", "div2" etc.
```
<ul>
<li><div class="hidden" id="div1"></li>
<li><div class="hidden" id="div1"></li>
...
</ul>
```
And there's another page with a menu, which consists of anchored links to every such a div:
```
<ul>
<li><a href="bibl.html#div1"></li>
<li><a href="bibl.html#div2"></li>
...
</ul>
```
I want the hidden div to autoexpand when the link on another page is clicked. I tried some window.location.href stuff, but to no avail - my JS is weak yet. As I understand the logic it should take the current url and check it for "#", then search for an element with the part to the right in the id attribute. Thanks a lot kind people.) | You can do something like this on the target page:
```
window.onload = function() {
var hash = window.location.hash; // would be "#div1" or something
if(hash != "") {
var id = hash.substr(1); // get rid of #
document.getElementById(id).style.display = 'block';
}
};
```
Essentially, you check on the page load whether the window's href has a hash attached to it. If it does, you find the `<div>` and change the style display to block. | Thank you! I figured out you can add this
```
location.href = '#' + id;
```
and also have the page scrolled to the position of the referred div. | Expanding a hidden div by referring with an anchor from external page | [
"",
"javascript",
"anchor",
"hidden",
""
] |
I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines:
```
*** E0710091001.DAT *** [0.67%]
*** E0710091001.DAT *** [1.33%]
*** E0710091001.DAT *** [2.00%]
*** E0710091001.DAT *** [2.66%]
*** E0710091001.DAT *** [3.33%]
*** E0710091001.DAT *** [3.99%]
*** E0710091001.DAT *** [4.66%]
*** E0710091001.DAT *** [5.32%]
*** E0710091001.DAT *** [5.99%]
*** E0710091001.DAT *** [6.65%]
*** E0710091001.DAT *** [7.32%]
*** E0710091001.DAT *** [7.98%]
*** E0710091001.DAT *** [8.65%]
*** E0710091001.DAT *** [9.32%]
*** E0710091001.DAT *** [9.98%]
*** E0710091001.DAT *** [10.65%]
*** E0710091001.DAT *** [11.31%]
*** E0710091001.DAT *** [11.98%]
*** E0710091001.DAT *** [12.64%]
*** E0710091001.DAT *** [13.31%]
*** E0710091001.DAT *** [13.97%]
*** E0710091001.DAT *** [14.64%]
*** E0710091001.DAT *** [15.30%]
*** E0710091001.DAT *** [15.97%]
*** E0710091001.DAT *** [16.63%]
*** E0710091001.DAT *** [17.30%]
*** E0710091001.DAT *** [17.97%]
*** E0710091001.DAT *** [18.63%]
```
I just want to know if I can tell from inside the script if it's being called from cron, and if so, I won't display this output. | See code below. Replace my print statements with what you want to show.
```
import sys
if sys.stdout.isatty():
print "Running from command line"
else:
print "Running from cron"
``` | you could create a flag. Possibly undocumented that your cron job would pass to the utility to structure the output. | How can I tell if my script is being run from a cronjob or from the command line? | [
"",
"python",
"cron",
""
] |
Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'project'?
Maybe some clever hacks in **init**.py?
Added:
It needs to be global - that is, other scripts loading 'project' via the standard:
```
import project
```
Have to work properly, loading a40bd22344 instead. | You first import it with **import**:
```
>>> __import__('temp/a40bd22344')
<module 'temp/a40bd22344' from 'temp/a40bd22344/__init__.py'>
```
Then you make sure that this module gets known to Python as `project`:
```
>>> import sys
>>> sys.modules['project'] = sys.modules.pop('temp/a40bd22344')
```
After this, anything importing project in the current Python session will get the original module
```
>>> import project
>>> project
<module 'temp/a40bd22344' from 'temp/a40bd22344/__init__.py'>
```
This will work also for sub-modules: if you have a foobar.py in the same location you'll get
```
>>> import project.foobar
>>> project.foobar
<module 'project.foobar' from 'temp/a40bd22344/foobar.py'>
```
**Addendum.** Here's what I'm running:
```
>>> print sys.version
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
``` | Here's one way to do it, without touching sys.path, using the `imp` module in Python:
```
import imp
f, filename, desc = imp.find_module('a40bd22344', ['/home/user/temp/'])
project = imp.load_module('a40bd22344', f, filename, desc)
project.some_func()
```
Here is a link to some good documentation on the `imp` module:
* *[imp — Access the import internals](http://docs.python.org/library/imp.html)* | Override namespace in Python | [
"",
"python",
"python-import",
""
] |
I am writing a Facebook application that is a simple board game which I have implemented in javascript. Facebook only seems to let javascript applications run within an iframe so I am loading the page using `<fb:iframe>`. I just want to be able to tell the javascript the user's id so I can tell the user if it is his turn or not but I can not find documentation on accessing facebook data from within the fb:iframe. I am probably missing some basic conecpt as I do not understand the facebook API very well. | Facebook's API is very tough to follow, and the documentation is very poor. You're right about the Javascript... normal Javascript only works inside an iframe on Facebook, otherwise you're limited to a subset of filtered Javascript called FBJS. You can safely ignore anything about FBJS in the documentation, and focus on iframes.
**Iframe loading**
The first thing I would mention is that an `<fb:iframe>` tag actually gets rendered with a ton of stuff in the `src` attribute. So if you put a tag like this into your Facebook page: `<fb:iframe src="http://example.com/page?x=y">`, what it ends up becoming when it loads into a user's browser is more like this:
`<iframe src="http://example.com/page?x=y&fb_sig_in_iframe=1&fb_sig_locale=en_US&fb_sig_in_new_facebook=1&fb_sig_time=1246340245.3338&fb_sig_added=1&fb_sig_profile_update_time=1242155811&fb_sig_expires=1246345200&fb_sig_user=000000001&fb_sig_session_key=2.d13uVGvWVL4hVAXELgxkZw__.3600.1246345200-000000001&fb_sig_ss=mZtFjaexyuyQdGnUz1zhYTA__&fb_sig_api_key=46899e6f07cef023b7fda4fg2e21bc58&fb_sig_app_id=22209322289&fb_sig=bbc165ebc699b12345678960fd043033">`
Facebook adds a ton of stuff to the src. The parameter that tells you the user's Facebook id is `fb_sig_user` (which is 000000001 here). I'm assuming your app is set up as an "FBML app", since you probably wouldn't use an `<fb:iframe>` tag in an "Iframe app". Nonetheless, the rendering method is similar in both cases, and you get a bunch of extra stuff to your `src` document in an "Iframe app" as well.
This really only passes you the Facebook user id on the first load of the iframe, however. Subsequent operations within the iframe won't have access to that user id unless you pass it around explicitly.
**Facebook Connect**
If you want to interact with Facebook from within the iframe, that's where the Facebook Connect Javascript libraries comes in. The best instructions on setting up Facebook Connect is probably [this wiki page](http://wiki.developers.facebook.com/index.php/JavaScript_Client_Library#Setting_Up_the_JavaScript_Client), but it's still a bit murky. Facebook Connect can be used for both completely external sites, or just regular content inside an iframe. You fall into the latter category, so if you follow the instructions in that link and use the first line of code in step 2 (for the FeatureLoader), you should be ok.
Once you've included the FeatureLoader.js script and called FB.init, you should generally be up and running with FB Connect. You should be able to interact with the [API](http://wiki.developers.facebook.com/index.php/API) from then on out. The `users.getLoggedInUser()` method will give you the current user id inside the iframe via Javascript.
Hope that helps. | Note that as of March 2011, FB is moving to POST requests to load iframes. It sends a form action with method="post" and target="iframe\_canvas", plus an input type="hidden" with a "signed\_request" | How to access Facebook user ID from javascript within a fb:iframe? | [
"",
"javascript",
"facebook",
"facebook-iframe",
""
] |
This code snippet is from C# in Depth
```
static bool AreReferencesEqual<T>(T first, T second)
where T : class
{
return first == second;
}
static void Main()
{
string name = "Jon";
string intro1 = "My name is " + name;
string intro2 = "My name is " + name;
Console.WriteLine(intro1 == intro2);
Console.WriteLine(AreReferencesEqual(intro1, intro2));
}
```
The output of the above code snippet is
```
True
False
```
When the main method is changed to
```
static void Main()
{
string intro1 = "My name is Jon";
string intro2 = "My name is Jon";
Console.WriteLine(intro1 == intro2);
Console.WriteLine(AreReferencesEqual(intro1, intro2));
}
```
The output of the above code snippet is
```
True
True
```
I cannot fathom why ?
EDIT: Once you understand string-interning following questions don't apply.
How are the parameters received at the Generic method `AreReferencesEqual` in the second code snippet ?
What changes to the string type when it is concatenated to make the == operator not call the overloaded Equals method of the String type ? | On the case of strings, you probably don't intend to use reference equality.
To access equality and inequality in generic methods, your best bet it:
```
EqualityComparer<T>.Default.Equals(x,y); // for equality
Comparer<T>.Default.Compare(x,y); // for inequality
```
i.e.
```
static bool AreValuesEqual<T>(T first, T second)
where T : class
{
return EqualityComparer<T>.Default.Equals(first,second);
}
```
This still uses the overloaded `Equals`, but handles nulls etc too. For inequality, this handles nulls, and both `IComparable<T>` and `IComparable`.
For other operators, see [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html).
---
Re the question; in the case of:
```
string intro1 = "My name is Jon";
string intro2 = "My name is Jon";
Console.WriteLine(intro1 == intro2);
Console.WriteLine(AreReferencesEqual(intro1, intro2));
```
You get `true`, `true` because the compiler and runtime is designed to be efficient with strings; any literals that you use are "interned" and the same instance is used every time in your AppDomain. The **compiler** (rather than runtime) also does the concat if possible - i.e.
```
string intro1 = "My name is " + "Jon";
string intro2 = "My name is " + "Jon";
Console.WriteLine(intro1 == intro2);
Console.WriteLine(AreReferencesEqual(intro1, intro2));
```
is **exactly the same code** as the previous example. There is no difference at all. However, if you force it to concatenate strings at runtime, it assumes they are likely to be short-lived, so they are *not* interned/re-used. So in the case:
```
string name = "Jon";
string intro1 = "My name is " + name;
string intro2 = "My name is " + name;
Console.WriteLine(intro1 == intro2);
Console.WriteLine(AreReferencesEqual(intro1, intro2));
```
you have 4 strings; "Jon" (interned), "My name is " (interned), and **two different instances** of "My name is Jon". Hence `==` returns true and reference equality returns false. But value-equality (`EqualityComparer<T>.Default`) would still return true. | Learnt a new thing today.
I guess Jon said in one of the questions, I tried to answer.
When you build a string using concatenation, == will return true for 2 strings of matching value but they don't point to the same reference (which I thought, it should due to string interning. Jon pointed that string interning works for constant or literals).
In the generic version, it is calling object.ReferenceEquals (which is different than ==. In case of string, == does value comparison).
As a result, the concatenated version returns false whereas the constant (literal string) version returns true.
EDIT: I think Jon must be around to explain this in a much better way :)
Lazy me, I have bought the book but have yet to get started on it. :( | Operator overloading in Generic Methods | [
"",
"c#",
".net",
"generics",
"string-interning",
""
] |
first time posting in StackOverflow. :D
I need my software to add a couple of things in the registry.
My program will use
> `Process.Start(@"blblabla.smc");`
to launch a file, but the problem is that most likely the user will not have a program set as default application for the particular file extension.
**How can I add file associations to the WindowsRegistry?** | In addition to the answers already provided, you can accomplish this by calling the command line programs "ASSOC" and "FTYPE". FTYPE associates a file type with a program. ASSOC associates a file extension with the file type specified through FTYPE. For example:
```
FTYPE SMCFile="C:\some_path\SMCProgram.exe" -some_option %1 %*
ASSOC .smc=SMCFile
```
This will make the necessary entries in the registry. For more information, type `ASSOC /?` or `FTYPE /?` at the command prompt. | Use the [`Registry`](http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.aspx) class in [`Microsoft.Win32`](http://msdn.microsoft.com/en-us/library/microsoft.win32.aspx).
Specifically, you want the [`ClassesRoot`](http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.classesroot.aspx) property of `Registry` to access the [`HKEY_CLASSES_ROOT`](http://msdn.microsoft.com/en-us/library/ms724475(VS.85).aspx) key (cf. [Understanding MS Windows File Associations](http://technet.microsoft.com/en-us/library/cc749986.aspx) and [HKEY\_CLASSES\_ROOT: Core Services](http://technet.microsoft.com/en-us/library/cc739822(WS.10).aspx)).
```
using Microsoft.Win32;
Registry
.ClassesRoot
.CreateSubKey(".smc")
.SetValue("", "SMC", RegistryValueKind.String);
Registry
.ClassesRoot
.CreateSubKey("SMC\shell\open\command")
.SetValue("", "SMCProcessor \"%1\"", RegistryValueKind.String);
```
Replace `"SMCProcessor \"%1\""` with the command-line path and argument specification for the program that you wish to associate with files with extension `.smc`.
But, instead of messing with the registry, why not just say
```
Process.Start("SMCProcessor blblabla.smc");
``` | How to change filetype association in the registry? | [
"",
"c#",
".net",
"registry",
"file-extension",
""
] |
Is it possible to allocate an arbitrary memory block using the "new" operator?
In C I can do it like "void \* p = malloc(7);" - this will allocate 7 bytes if memory alignment is set to 1 byte. How to make the same in C++ with the new operator? | Arbitrary memory blocks can be allocated with `operator new` in C++; not with the `new` operator which is for constructing objects.
```
void* pBlock = ::operator new(7);
```
Such blocks can subsequently be freed with `operator delete`.
```
::operator delete(pBlock);
```
Note that `operator new` will allocated memory suitably aligned for any sort of object, so the implementation might not allocate exactly seven bytes and no more, but the same is (usually) true of `malloc`. C clients of `malloc` usually need aligned memory too. | Others have answered the question as written but I'd like to suggest sticking with malloc/free for such allocations.
new and delete are for allocating objects. They allocate the memory required and call constructors/destructors. If you know that you just need an arbitrary block of memory, using malloc and free is perfectly reasonable. | memory allocation in C++ | [
"",
"c++",
"memory",
"new-operator",
""
] |
I would like to see if an object is a [builtin data type](http://msdn.microsoft.com/en-us/library/cs7y5x0x.aspx) in C#
I don't want to check against all of them if possible.
That is, I *don't* want to do this:
```
Object foo = 3;
Type type_of_foo = foo.GetType();
if (type_of_foo == typeof(string))
{
...
}
else if (type_of_foo == typeof(int))
{
...
}
...
```
**Update**
I'm trying to recursively create a PropertyDescriptorCollection where the PropertyDescriptor types might not be builtin values. So I wanted to do something like this (note: this doesn't work yet, but I'm working on it):
```
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
PropertyDescriptorCollection cols = base.GetProperties(attributes);
List<PropertyDescriptor> list_of_properties_desc = CreatePDList(cols);
return new PropertyDescriptorCollection(list_of_properties_desc.ToArray());
}
private List<PropertyDescriptor> CreatePDList(PropertyDescriptorCollection dpCollection)
{
List<PropertyDescriptor> list_of_properties_desc = new List<PropertyDescriptor>();
foreach (PropertyDescriptor pd in dpCollection)
{
if (IsBulitin(pd.PropertyType))
{
list_of_properties_desc.Add(pd);
}
else
{
list_of_properties_desc.AddRange(CreatePDList(pd.GetChildProperties()));
}
}
return list_of_properties_desc;
}
// This was the orginal posted answer to my above question
private bool IsBulitin(Type inType)
{
return inType.IsPrimitive || inType == typeof(string) || inType == typeof(object);
}
``` | Well, one easy way is to just explicitly list them in a set, e.g.
```
static readonly HashSet<Type> BuiltInTypes = new HashSet<Type>
(typeof(object), typeof(string), typeof(int) ... };
...
if (BuiltInTypes.Contains(typeOfFoo))
{
...
}
```
I have to ask why it's important though - I can understand how it might make a difference if it's a [.NET primitive type](http://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx), but could you explain why you would want your application to behave differently if it's one of the ones for C# itself? Is this for a development tool?
Depending on the answer to that question, you might want to consider the situation with `dynamic` in C# 4 - which isn't a type at execution time as such, but is `System.Object` + an attribute when applied to a method parameter etc. | Not directly but you can do the following simplified check
```
public bool IsBulitin(object o) {
var type = o.GetType();
return (type.IsPrimitive && type != typeof(IntPtr) && type != typeof(UIntPtr))
|| type == typeof(string)
|| type == typeof(object)
|| type == typeof(Decimal);
}
```
The IsPrimitive check will catch everything but string, object and decimal.
**EDIT**
While this method works, I would prefer Jon's solution. The reason is simple, check the number of edits I had to make to my solution because of the types I forgot were or were not primitives. Easier to just list them all out explicitly in a set. | Is there a function to check if an object is a builtin data type? | [
"",
"c#",
"types",
"built-in",
"built-in-types",
""
] |
Suppose I have this (C++ or maybe C) code:
```
vector<int> my_vector;
for (int i = 0; i < my_vector.size(); i++) {
my_vector[i] = 0;
}
```
I don't care if it's done right. The important part is in the for-loop declaration.
The compiler gives a signed/unsigned mismatch for this, since size() returns an unsigned int, not a signed one. How important is it to change `i` to unsigned? I declare loop counters as ints out of habit, but if this is a potential error I'll force myself to get out of the habit. | I would say it's very important - you should be compiling with warnings as errors, and strive to fix all warnings. If you leave problems like this in your code, it is easy to get into a habit of ignoring warnings, or letting false positives like this drown out warnings that indicate real problems.
In this case, for this specific error, it's probably not a big deal - on a 32-bit platform you'd have to have more than 2 billion entries in the vector before the unsigned would wrap into a negative signed value. To get a vector like this would exhaust all of your memory, so it's probably not possible to get into a state where signed/unsigned mismatch would matter. | Technically, `i` should be a `vector<int>::size_type`. You should get in the habit of using `typedef`s in your code:
```
typedef vector<int> VectorType;
VectorType my_vector;
for (VectorType::size_type i = 0; i < my_vector.size(); i++) {
my_vector[i] = 0;
}
```
Now, if we change it to a `deque`, we only change one line. Even if it's some custom container that has a wacky size\_type, you get the warm, fuzzy feeling that everything will be ok. And that's worth a lot. Even with just unsigned/signed, there are some tricky promotion issues with using signed/unsigned conversion that will inevitably come back to bite you. | Compiler warnings | [
"",
"c++",
"compiler-warnings",
"unsigned",
"signed",
""
] |
I use `boost::shared_ptr` in my application in C++. The memory problem is really serious, and the application takes large amount of memory.
However, because I put every newed object into a `shared_ptr`, when the application exits, no memory leaking can be detected.
There must be something like `std::vector<shared_ptr<> >` pool holding the resource. How can I know who holds the `shared_ptr`, when debugging?
It is hard to review code line by line. Too much code... | You can't know, by only looking at a `shared_ptr`, where the "sibling pointers" are. You can test if one is `unique()` or get the `use_count()`, among [other methods](http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_ptr.htm#Synopsis). | The popular widespread use of `shared_ptr` will almost inevitably cause unwanted and unseen memory occupation.
Cyclic references are a well known cause and some of them can be indirect and difficult to spot especially in complex code that is worked on by more that one programmer; a programmer may decide than one object needs a reference to another as a quick fix and doesn't have time to examine all the code to see if he is closing a cycle. This hazard is hugely underestimated.
Less well understood is the problem of unreleased references. If an object is shared out to many `shared_ptrs` then it will not be destroyed until every one of them is zeroed or goes out of scope. It is very easy to overlook one of these references and end up with objects lurking unseen in memory that you thought you had finished with.
Although strictly speaking these are not memory leaks (it will all be released before the program exits) they are just as harmful and harder to detect.
These problems are the consequences of expedient false declarations:
1. Declaring what you really want to be single ownership as `shared_ptr`. `scoped_ptr` would be correct but then any other reference to that object will have to be a raw pointer, which could be left dangling.
2. Declaring what you really want to be a passive observing reference as `shared_ptr`. `weak_ptr` would be correct but then you have the hassle of converting it to `share_ptr` every time you want to use it.
I suspect that your project is a fine example of the kind of trouble that this practice can get you into.
If you have a memory intensive application you really need single ownership so that your design can explicitly control object lifetimes.
With single ownership `opObject=NULL;` will definitely delete the object and it will do it now.
With shared ownership `spObject=NULL;` ........who knows?...... | How do I know who holds the shared_ptr<>? | [
"",
"c++",
"boost",
"memory-leaks",
"shared-ptr",
""
] |
Using javascript, how do I add some data to the query string?
Basically I want to add the window.screen.height and window.screen.width info to the query string so that I can then email it with the other login info.
Alternatively, how would I populate a couple of hidden fields with the same data, a form is being submitted so I could pick it up from there?
Thanks, R. | I think that the latter option would be easier to implement. For example, if you have the hidden fields like this:
```
...
<input type="hidden" name="screenheight" id="screenheight" value="" />
<input type="hidden" name="screenwidth" id="screenwidth" value="" />
...
```
Then the JavaScript would be:
```
<script type="text/javascript">
document.getElementById('screenheight').value = window.screen.height;
document.getElementById('screenwidth').value = window.screen.width;
</script>
``` | You can also use [jquery.query.js](http://code.google.com/p/multi-doc/source/browse/trunk/static/jquery-query.js?spec=svn19&r=19) to play with querystring. | Query String Javascript | [
"",
"javascript",
""
] |
I'm attempting to solve the Project Euler [Problem 8](https://projecteuler.net/problem=8) with C++, and the problem is to find the greatest product of 5 consecutive numbers in a 1000 digit number. So I'm trying to figure out how to use file io to read the numbers into a char array that I will later convert to integers. The read works except for the last third of the last line I get weird lines, a green lantern symbol, and a heart.

```
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
const int maxNum = 1000;
char buffer[maxNum];
char *bufferPointer = buffer;
ifstream infile;
infile.open("numberlist.txt");
if (!infile)
{
cerr << "Error: Open file failure" << endl;
return -1;
}
infile.read(bufferPointer, streamsize(maxNum));
infile.close();
cout << buffer << endl;
return 0;
}
```
This is what the txt file contains:
```
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
```
EDIT: Right after I posted this problem I just realized the problem might be the fact that read is reading the new lines and thus the array isn't big enough to hold it all. | Two problems with your code.
First, it looks like you're not accounting for newlines in your maxNum buffer size, so it stops reading either 19 or 38 characters before the end of the text file (depending on if you're using Unix-style or Windows-style line breaks). Either increase the value of maxNum accordingly, or remove the line breaks from your text file.
Second, since you're using a char array instead of a std::string to hold the buffer, it needs to be null-terminated to display properly if you use the stream operator. Add the following line after you read the buffer in (you'll also need to increase your buffer size by one to account for the extra character).
```
buffer[maxNum-1] = '\0';
```
Alternatively, you can use cout.write() to display a known-length buffer that's not null-terminated, as follows:
```
cout.write(buffer, maxNum);
``` | Well, this is not very idiomatic C++, you might get nice results if you switched to using std::string instead of a plain array of char's
This would probably fix the problem.
Which is that the list of numbers is more that 1000 characters long, and so does not fit in your buffer. | Reading input from file prints strange symbols | [
"",
"c++",
"file-io",
""
] |
Sorry if the post title wasn't clear, I will try to explain a little better here.
I am working with a web control that is databound to a data table. The output of the data is as such:
```
<asp:Repeater ID="RssRepeater" Visible="false" EnableViewState="false" runat="server">
<asp:literal ID="sb_description" Text='<%# DataBinder.Eval (Container.DataItem, "description") %>' EnableViewState="false" runat="server" />
''// Rest of structure...
</asp:Repeater>
```
I wrote a function that, in theory, should trim a passed string to a specified number of words:
```
protected string CreateTeaser(string Post)
{
int wordLimit = 50;
System.Text.StringBuilder oSB = new System.Text.StringBuilder();
string[] splitBy = new string[] { " " };
string[] splitPost = Post.Split(splitBy,
System.StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i <= wordLimit - 1; i++)
{
oSB.Append(string.Format("{0}{1}", splitPost[i],
(i < wordLimit - 1) ? " " : ""));
}
oSB.Append(" ...");
return oSB.ToString();
}
```
I tried this abomination:
```
<asp:literal ID="sb_description" Text='<%= CreateTeaser(%> <%# DataBinder.Eval (Container.DataItem, "description") %><%=); %>' EnableViewState="false" runat="server" />
```
But of course it did not work. So, is it possible to use this function on the `Databinder.Eval( ... )` while it is inside this literal control? If so, how should I go about doing this? If not, what would be a possible alternative to what I am trying to do?
Thanks SO! | You can submit the `Eval` result directly to your method (using your original `Eval` syntax and casting to a string):
```
<asp:literal
ID="sb_description"
Text='<%= CreateTeaser((string)DataBinder.Eval (Container.DataItem, "description")) %>'
EnableViewState="false"
runat="server"
/>
``` | It would be a lot easier to do that in the [RowDataBound](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx) event. | Is it possible to modify Databound content on the fly? | [
"",
"c#",
"asp.net",
""
] |
I have an array of bytes and i want to determine if the contents of this array of bytes exists within another larger array as a continuous sequence. What is the simplest way to go about doing this? | The naive approach is:
```
public static bool IsSubsetOf(byte[] set, byte[] subset) {
for(int i = 0; i < set.Length && i + subset.Length <= set.Length; ++i)
if (set.Skip(i).Take(subset.Length).SequenceEqual(subset))
return true;
return false;
}
```
For more efficient approaches, you might consider more advanced string matching algorithms like [KMP](http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm). | Try to adapt some string search algorithm. One of the fastest is [Boyer-Moore](http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm) . It's quite easy as well. For binary data, [Knuth-Morris-Pratt](http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) algorithm might work very efficiently as well. | C# Array Subset fetching | [
"",
"c#",
"algorithm",
"arrays",
"search",
""
] |
In ASP.NET MVC, how can I create a single cookie and save multplie values to it?
Thanks!! | ```
var cookie = new HttpCookie();
cookie.Values["FirstKey"] = value1;
cookie.Values["SecondKey"] = value2;
```
or a shortcut:
```
cookie["ThirdKey"] = value3;
```
HttpCookie.Values is a NameValueCollection, a class that appears in many places in ASP.NET MVC. Read [this](http://dotnetperls.com/namevaluecollection) for a good tutorial on how to use it to its full potential. | This problem can be rephrased as: "How can I store multiple values in a single string?"
It's up to you to come up with a system. If the values are simples numbers or strings, use a separator like a ";" and then split later. | How can I create a single cookie and save multiple pairs key/values to it? | [
"",
"c#",
"asp.net-mvc",
"cookies",
""
] |
what is the easiest way to figure out if a string ends with a certain value? | you could use Regexps, like this:
```
str.match(/value$/)
```
which would return true if the string has 'value' at the end of it ($). | Stolen from prototypejs:
```
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
'slaughter'.endsWith('laughter');
// -> true
``` | JavaScript or jQuery string ends with utility function | [
"",
"javascript",
"jquery",
""
] |
I am using the following code to apply a hover effect to a set of images within a div called toolbar:
```
$("#toolbar img").hover(
function()
{
this.src = this.src.replace("_off", "_on");
},
function()
{
this.src = this.src.replace("_on", "_off");
}
);
```
But I also want to apply the same effect to a div called tabs without repeating the same code. cant I do something along these lines:
```
$("#toolbar, #tabs img").hover(
function()
{
this.src = this.src.replace("_off", "_on");
},
function()
{
this.src = this.src.replace("_on", "_off");
}
);
```
The problem is the above only applies to the "tabs" div, while the toolbar stops working. I think I am just getting the jQuery syntax wrong, still sorta new to jQuery | You separate multiple selectors by commas as you did. If you want to recreate the effect as it was in the first example it needs to be:
```
$("#toolbar img, #tabs img")
```
'#toolbar img' is the entire selector. It says "apply this to any img tags that are in a parent element with the id of toolbar". E.g.:
```
<div id ="toolbar">
<img .../>
<img .../>
</div>
```
#tabs img, is a whole other selector.
These are the same syntax as CSS selectors, so for more information research that. | Try `$("#toolbar img, #tabs img")`. | How do I use multiple selectors in jQuery? | [
"",
"javascript",
"jquery",
""
] |
This is a C++ class that I have made with n number of pointers.
```
class SomeClass
{
private:
int* ptr1;
int* ptr2;
...
int* ptrn;
private:
// constructors, destructors, and methods
};
```
During the initialization stage, I want to make all those pointers point to NULL (or make pointers point to NULL by default when they are declared) rather than doing so:
```
void SomeClass::MakePtrNull()
{
ptr1 = NULL;
ptr2 = NULL;
...
ptrn = NULL;
}
```
Is there any easy method of accomplishing this goal? I'm just wondering if there are any ways of avoiding typing n lines of ptr = NULL; in my function. Thanks in advance.
**ADDED** based on the answers that I have received so far:
Unfortunately, those pointers have to be separate, as they are used for different purposes. I made the names of the pointers as such just to make a point of what I'm trying to do, but each pointer has a completely different purpose. I guess I would have to make them point to NULL as I have done already. Thanks for your answers. | Why don't you use an array or a vector rather than creating n individually named pointers? Then you can do the nulling in a short for loop. | Instead of `int *`, create a smart-pointer-like class which works exactly like a `int *`, but default-constructs with NULL:
```
template <typename T>
class MyPointer {
T *p;
public:
MyPointer() : p(NULL) { }
MyPointer(T *o) : p(o) { }
operator T*() const { return p; }
// ...and the rest of the traditional smart-pointer operators
};
```
Then, use it in your class:
```
class SomeClass
{
private:
MyPointer<int> ptr1;
MyPointer<int> ptr2;
...
MyPointer<int> ptrn;
private:
// constructors, destructors, and methods
};
```
Every variable of the `MyPointer<int>` type will be automatically initialized correctly in `SomeClass`'s constructors, without the need for any extra typing. If you did not forget or incorrectly implement any of `MyPointer`'s methods, it will act exactly like a normal pointer, and have the exact same size and performance. | making numerous pointers NULL at the same time | [
"",
"c++",
"pointers",
""
] |
Sounds like a stupid question with an obvious answer :)
Still I've ventured to ask just be doubly sure.
We are indeed using asserts like given below
```
ArrayList alProperties = new ArrayList();
assert alProperties != null : "alProperties is null";
```
Problem is that making a small & simple document to follow, on asserts is difficult. There are many books on asserts, but ideally I like to give a new programmer very simple guidelines on using something like asserts. Btw, does some tool like pmd check for proper usage of asserts?
Thanks in advance. | There's no sane reason to use asserts like that. If the object won't be created for some reason, your assert won't even be reached (because an exception was thrown or the VM exited, for example) | There are some fairly concise guidelines on using assertions in Sun's [Programming with Assertions](http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html). That article advises that asserts should be used for things like Internal Invariants, Control-Flow Invariants, and Preconditions, Postconditions, and Class Invariants. | Should we assert every object creation in java? | [
"",
"java",
"new-operator",
"assert",
""
] |
My application often fetch data from a webpage using WebRequest, but it isn't possible to click buttons etc while it's fetching. I've understood that I have to use threads/a backgroundworker, but I can't get it to work properly; it doesn't make the GUI more respondable.
The code I want to apply some kind of threading on, so that it stops making my application unresponding:
```
public string SQLGet(string query)
{
string post = "q=" + query;
WebRequest request = WebRequest.Create("http://test.com");
request.Timeout = 20000;
request.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(post);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
requestStream = response.GetResponseStream();
StreamReader reader = new StreamReader(requestStream);
string ret = reader.ReadToEnd();
reader.Close();
requestStream.Close();
response.Close();
return ret;
}
```
---
Edit: Thank you, lc, I had tried something pretty similar to that. But my problem with using the backgroundworker like that is; how do I get the queryResult back to the function which called (in my case SQLGet, and in your case) StartQuery?
In my example, the returned string is going to be used as a local variable in the void the string is called inside.
And there may be many queries at the same time, so I don't want to risk assigning it to a global variable. | Here's a simple example of how to use the [`BackgroundWorker`](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) as it applies to your code:
```
private void StartQuery(string query)
{
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.RunWorkerAsync(query);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = SQLGet((string)e.Argument);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
queryResult = (string)e.Result;
}
```
You may also wish to allow cancellation, provide error details, or provide robust feedback as it fetches data. Take a look at the example [on the MSDN page](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) for more details.
The result of your query will show up in the `BackgroundWorker.RunWorkerCompleted` event as `e.Result` (I've stored it as an instance variable in this case). If you're going to run many of these at the same time, you'll need a way to differentiate which query is which. So you should pass more than just a string to the method. Take this example:
```
private int NextID = 0;
private struct QueryArguments
{
public QueryArguments()
{
}
public QueryArguments(int QueryID, string Query)
: this()
{
this.QueryID = QueryID;
this.Query = Query;
}
public int QueryID { get; set; }
public string Query { get; set; }
public string Result { get; set; }
}
private int StartQuery(string query)
{
QueryArguments args = new QueryArguments(NextID++, query);
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.RunWorkerAsync(args);
return args.QueryID;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
QueryArguments args = (QueryArguments)e.Argument;
args.Result = SQLGet(args.Query);
e.Result = args;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
QueryArguments args = (QueryArguments)e.Result;
//args.Result contains the result
//do something
}
``` | BackgroundWorker is a good solution, with some built-in support for cancellation and progress. You can also just use HttpWebRequest.BeginGetResponse, rather than GetResponse, to initiate an asynchronous web request operation. This ends up being quite simple and you can set up a progress callback.
For an exact example of what you're trying to do, see:
[Using HttpWebRequest for Asynchronous Downloads](http://stuff.seans.com/2009/01/05/using-httpwebrequest-for-asynchronous-downloads/) | GUI not responding while fetching data | [
"",
"c#",
"winforms",
"multithreading",
"backgroundworker",
"webrequest",
""
] |
in my attempt to learn a bit faster the use of spring and hibernate i read few chapter on books and created a simple java project from netbeans 6.7.
I've decided to use the hibernate annotations instead of mapping files.so in my pojo i import javax.persistence.\*; and i have an error that javax doesn't exist.what sound surprising to me.is it because it's a simple java application? i come from .Net background and the main idea about this mini project is to consume (DAOs) it as i would use a class library project in .Net.How to solve or i would just have to create another project type. if yes which one? thanks for reading. | Which edition of NetBeans did you install? Did you install the one with Java Web and EE support? The Java Persistence API is part of Java EE, so the standard Java SE installation won't have the necessary libraries packaged. | This sounds like a classpath issue. are you adding the jar with javax.persistence to your classpath | Javax package and simple java application with spring hibernate | [
"",
"java",
"hibernate",
"spring",
"jakarta-ee",
""
] |
In C# i have a picturebox. i would like to draw 4 colors. The default will be white, red, green, blue. How do i draw these 4 colors stritched in this picbox? or should i have 4 picbox? in that case how do i set the rgb color? | You need to specify what it is you would specifically like to draw. You can't draw a red - that makes no sense. You can, however, draw a red rectangle at location (0,0) which is 100 pixels tall and 100 wide. I will answer what I can, however.
If you want to set the outline of a shape to a specific color, you would create a [Pen](http://msdn.microsoft.com/en-us/library/system.drawing.pen.aspx) object. If you want to fill a shape with a color, however, then you would use a Brush object. Here's an example of how you would draw a rectangle filled with red, and a rectangle outlined in green:
```
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
Brush brush = new SolidBrush(Color.Red);
graphics.FillRectangle(brush, new Rectangle(10, 10, 100, 100));
Pen pen = new Pen(Color.Green);
graphics.DrawRectangle(pen, new Rectangle(5, 5, 100, 100));
}
``` | Add a PictureBox to the form, create an event handler for the paint event, and make it look like this:
```
private void PictureBox_Paint(object sender, PaintEventArgs e)
{
int width = myPictureBox.ClientSize.Width / 2;
int height = myPictureBox.ClientSize.Height / 2;
Rectangle rect = new Rectangle(0, 0, width, height);
e.Graphics.FillRectangle(Brushes.White, rect);
rect = new Rectangle(width, 0, width, height);
e.Graphics.FillRectangle(Brushes.Red, rect);
rect = new Rectangle(0, height, width, height);
e.Graphics.FillRectangle(Brushes.Green, rect);
rect = new Rectangle(width, height, width, height);
e.Graphics.FillRectangle(Brushes.Blue, rect);
}
```
This will divide the surface into 4 rectangles and paint each of them in the colors White, Red, Green and Blue. | Drawing Colors in a picturebox? | [
"",
"c#",
"graphics",
"drawing",
"picturebox",
""
] |
I have this piece of code that does not work:
```
public CartaoCidadao()
{
InitializeComponent();
object o = WebDAV.Classes.SCWatcher.LoadAssembly();
MethodInfo method =
this.GetType().GetMethod("Inserted",
BindingFlags.NonPublic | BindingFlags.Instance);
EventInfo eventInfo = o.GetType().GetEvent("CardInserted");
Type type = eventInfo.EventHandlerType;
Delegate handler = Delegate.CreateDelegate(type, this , method);
eventInfo.AddEventHandler(o, handler);
}
void Inserted(string readerName, string cardName)
{
System.Windows.Forms.MessageBox.Show(readerName);
}
```
The Event CardInserted exists in another DLL file and object "o" loads OK. The delegate handler has a value after effect. I only can't fire the event. | Here's a sample showing how to attach an event using reflection:
```
class Program
{
static void Main(string[] args)
{
var p = new Program();
var eventInfo = p.GetType().GetEvent("TestEvent");
var methodInfo = p.GetType().GetMethod("TestMethod");
Delegate handler =
Delegate.CreateDelegate(eventInfo.EventHandlerType,
p,
methodInfo);
eventInfo.AddEventHandler(p, handler);
p.Test();
}
public event Func<string> TestEvent;
public string TestMethod()
{
return "Hello World";
}
public void Test()
{
if (TestEvent != null)
{
Console.WriteLine(TestEvent());
}
}
}
``` | Here's a short but complete example which *does* work:
```
using System;
using System.Reflection;
class EventPublisher
{
public event EventHandler TestEvent;
public void RaiseEvent()
{
TestEvent(this, EventArgs.Empty);
}
}
class Test
{
void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("HandleEvent called");
}
static void Main()
{
// Find the handler method
Test test = new Test();
EventPublisher publisher = new EventPublisher();
MethodInfo method = typeof(Test).GetMethod
("HandleEvent", BindingFlags.NonPublic | BindingFlags.Instance);
// Subscribe to the event
EventInfo eventInfo = typeof(EventPublisher).GetEvent("TestEvent");
Type type = eventInfo.EventHandlerType;
Delegate handler = Delegate.CreateDelegate(type, test, method);
// Raise the event
eventInfo.AddEventHandler(publisher, handler);
publisher.RaiseEvent();
}
}
```
Now, when you say "I only can't fire event", what exactly do you mean? You're not meant to be able to raise events yourself - it's up to the event publisher to do that. Does all of the code you've actually presented to us work? If so, it seems that it's not adding the event handler that's the problem.
Could you give more information? | AddEventHandler using reflection | [
"",
"c#",
".net",
"events",
"reflection",
""
] |
I want to know if the below code:
```
<?php
printf ("%s", $some_variable);
?>
```
is more efficient than:
```
<?php
echo "$some_variable";
?>
```
One common complaint of variable interpolation is that it is very slow. I want to know if there is a better alternative to variable interpolation that doesn't make one's code as messy as:
```
<?php
echo $first_var, ' some string ', $second_var;
?>
``` | The argument among variable interpolation, string concatenation, multiple-parameter passing, and s?printf is, for a lack of a better word, stupid. Don't worry about this trivial micro-optimization until it becomes the memory/speed bottleneck, which it will never become. So effectively just use whatever you want, factoring in readability, discernibility and plain preference. | Quick test:
```
$ cat test-echo.php
<?
$i=10000000;
$some_variable = 'test';
while($i--){
echo "$some_variable";
}
$ cat test-echo2.php
<?
$i=10000000;
$some_variable = 'test';
while($i--){
echo $some_variable;
}
$ cat test-printf.php
<?
$i=10000000;
$some_variable = 'test';
while($i--){
printf ("%s", $some_variable);
}
$ time php test-echo.php > /dev/null
real 0m16.099s
user 0m8.254s
sys 0m4.257s
$ time php test-echo2.php > /dev/null
real 0m15.122s
user 0m6.913s
sys 0m4.037s
$ time php test-printf.php > /dev/null
real 0m48.235s
user 0m30.643s
sys 0m11.614s
```
So printf significantly is slower than simple echo.
echo with variable interpolation is a bit slower than simple echo. Difference in not noticable, probably because of poor test case. | In PHP, is printf more efficient than variable interpolation? | [
"",
"php",
"optimization",
""
] |
i have a problem with my code.
```
foreach (DataRow dr in dt_pattern.Rows)
{
part = dr["patternString"].ToString();
if (part != vpart)
{
System.Console.WriteLine(part);
System.Console.WriteLine("Geben Sie bitte für den Abschnitt die AT ein: ");
temp = System.Console.ReadLine();
AT = ToDouble(temp);
dr["AT"] = AT;
double xATmax = ToDouble(dr["Ampl"].ToString());
double x = ToDouble(dr["Time"].ToString());
double yATmax = ToDouble(dr["Ampl"]+1.ToString()) + AT;
double y = ToDouble(dr["Ampl"].ToString());
dr["alphaATmin"] = Gradient(x,xATmax,y,yATmax);
System.Console.WriteLine(dr["alphaATmin"]);
}
vpart = part;
}
```
but i need at xATmax and yATmax the Value of the next Row... Someone can help me ? | Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...
```
for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}
```
Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that. | ```
for (int i=0; i<dt_pattern.Rows.Count; i++)
{
DataRow dr = dt_pattern.Rows[i];
}
```
In the loop, you can now reference row i+1 (assuming there is an i+1) | Get Value of Row in Datatable c# | [
"",
"c#",
"datatable",
"gradient",
"datarow",
""
] |
> **Possible Duplicate:**
> [What is the best Twitter API wrapper/library for .NET?](https://stackoverflow.com/questions/685015/what-is-the-best-twitter-api-wrapper-library-for-net)
My boss wants to make periodic updates to the company twitter account but doesn't really want to mess with it through the web or follow others.
I'm sure there is plenty of info but I thought I would start out by asking the experts
is there a twitter class or dll that I can use to do simple posting via twitter?
(similar to the flicker.net librarby?) | Check out [tweetsharp.com](http://tweetsharp.com/) - sounds like it could be just what you're looking for. | Start reading about the [Twitter REST API Method: statuses/update](http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0update). All you need to do is formulate the proper WebRequests (one for authentication, one for the update).
> Updates the authenticating user's
> status. Requires the status parameter
> specified below. Request must be a
> POST. A status update with text
> identical to the authenticating user's
> current status will be ignored to
> prevent duplicates.
Something along the lines of:
```
http://twitter.com/statuses/update.xml
``` | upload a tweet using C# | [
"",
"c#",
".net",
"twitter",
""
] |
I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a `Ctrl`+`C` signal, and I'd like to do some cleanup.
In Perl I'd do this:
```
$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
```
How do I do the analogue of this in Python? | Register your handler with [`signal.signal`](https://docs.python.org/3/library/signal.html#signal.signal) like this:
```
#!/usr/bin/env python
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
```
Code adapted from [here](http://www.linuxjournal.com/article/3946).
More documentation on `signal` can be found [here](http://docs.python.org/library/signal.html). | You can treat it like an exception (`KeyboardInterrupt`), like any other. Make a new file and run it from your shell with the following contents to see what I mean:
```
import time, sys
x = 1
while True:
try:
print x
time.sleep(.3)
x += 1
except KeyboardInterrupt:
print "Bye"
sys.exit()
``` | How do I capture SIGINT in Python? | [
"",
"python",
"signals",
""
] |
Suppose I have this function:
```
void my_test()
{
A a1 = A_factory_func();
A a2(A_factory_func());
double b1 = 0.5;
double b2(0.5);
A c1;
A c2 = A();
A c3(A());
}
```
In each grouping, are these statements identical? Or is there an extra (possibly optimizable) copy in some of the initializations?
I have seen people say both things. Please **cite** text as proof. Also add other cases please. | ## C++17 Update
In C++17, the meaning of `A_factory_func()` changed from creating a temporary object (C++<=14) to just specifying the initialization of whatever object this expression is initialized to (loosely speaking) in C++17. These objects (called "result objects") are the variables created by a declaration (like `a1`), artificial objects created when the initialization ends up being discarded, or if an object is needed for reference binding (like, in `A_factory_func();`. In the last case, an object is artificially created, called "temporary materialization", because `A_factory_func()` doesn't have a variable or reference that otherwise would require an object to exist).
As examples in our case, in the case of `a1` and `a2` special rules say that in such declarations, the result object of a prvalue initializer of the same type as `a1` is variable `a1`, and therefore `A_factory_func()` directly initializes the object `a1`. Any intermediary functional-style cast would not have any effect, because `A_factory_func(another-prvalue)` just "passes through" the result object of the outer prvalue to be also the result object of the inner prvalue.
---
```
A a1 = A_factory_func();
A a2(A_factory_func());
```
Depends on what type `A_factory_func()` returns. I assume it returns an `A` - then it's doing the same - except that when the copy constructor is explicit, then the first one will fail. Read [8.6/14](http://eel.is/c++draft/dcl.init#14)
```
double b1 = 0.5;
double b2(0.5);
```
This is doing the same because it's a built-in type (this means not a class type here). Read [8.6/14](http://eel.is/c++draft/dcl.init#14).
```
A c1;
A c2 = A();
A c3(A());
```
This is not doing the same. The first default-initializes if `A` is a non-POD, and doesn't do any initialization for a POD (Read [8.6/9](http://eel.is/c++draft/dcl.init#9)). The second copy initializes: Value-initializes a temporary and then copies that value into `c2` (Read [5.2.3/2](http://eel.is/c++draft/expr.type.conv#2) and [8.6/14](http://eel.is/c++draft/dcl.init#14)). This of course will require a non-explicit copy constructor (Read [8.6/14](http://eel.is/c++draft/dcl.init#14) and [12.3.1/3](http://eel.is/c++draft/class.conv.ctor#3) and [13.3.1.3/1](http://eel.is/c++draft/over.match.ctor#1) ). The third creates a function declaration for a function `c3` that returns an `A` and that takes a function pointer to a function returning a `A` (Read [8.2](http://eel.is/c++draft/dcl.ambig.res)).
---
**Delving into Initializations** Direct and Copy initialization
While they look identical and are supposed to do the same, these two forms are remarkably different in certain cases. The two forms of initialization are direct and copy initialization:
```
T t(x);
T t = x;
```
There is behavior we can attribute to each of them:
* Direct initialization behaves like a function call to an overloaded function: The functions, in this case, are the constructors of `T` (including `explicit` ones), and the argument is `x`. Overload resolution will find the best matching constructor, and when needed will do any implicit conversion required.
* Copy initialization constructs an implicit conversion sequence: It tries to convert `x` to an object of type `T`. (It then may copy over that object into the to-initialized object, so a copy constructor is needed too - but this is not important below)
As you see, *copy initialization* is in some way a part of direct initialization with regard to possible implicit conversions: While direct initialization has all constructors available to call, and *in addition* can do any implicit conversion it needs to match up argument types, copy initialization can just set up one implicit conversion sequence.
I tried hard and [got the following code to output different text for each of those forms](http://coliru.stacked-crooked.com/a/708ae8b380c63ba8), without using the "obvious" through `explicit` constructors.
```
#include <iostream>
struct B;
struct A {
operator B();
};
struct B {
B() { }
B(A const&) { std::cout << "<direct> "; }
};
A::operator B() { std::cout << "<copy> "; return B(); }
int main() {
A a;
B b1(a); // 1)
B b2 = a; // 2)
}
// output: <direct> <copy>
```
How does it work, and why does it output that result?
1. **Direct initialization**
It first doesn't know anything about conversion. It will just try to call a constructor. In this case, the following constructor is available and is an *exact match*:
```
B(A const&)
```
There is no conversion, much less a user defined conversion, needed to call that constructor (note that no const qualification conversion happens here either). And so direct initialization will call it.
2. **Copy initialization**
As said above, copy initialization will construct a conversion sequence when `a` has not type `B` or derived from it (which is clearly the case here). So it will look for ways to do the conversion, and will find the following candidates
```
B(A const&)
operator B(A&);
```
Notice how I rewrote the conversion function: The parameter type reflects the type of the `this` pointer, which in a non-const member function is to non-const. Now, we call these candidates with `x` as argument. The winner is the conversion function: Because if we have two candidate functions both accepting a reference to the same type, then the *less const* version wins (this is, by the way, also the mechanism that prefers non-const member function calls for non-const objects).
Note that if we change the conversion function to be a const member function, then the conversion is ambiguous (because both have a parameter type of `A const&` then): The Comeau compiler rejects it properly, but GCC accepts it in non-pedantic mode. Switching to `-pedantic` makes it output the proper ambiguity warning too, though. | **Assignment** is different from **initialization**.
Both of the following lines do *initialization*. A single constructor call is done:
```
A a1 = A_factory_func(); // calls copy constructor
A a1(A_factory_func()); // calls copy constructor
```
but it's not equivalent to:
```
A a1; // calls default constructor
a1 = A_factory_func(); // (assignment) calls operator =
```
I don't have a text at the moment to prove this but it's very easy to experiment:
```
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << "default constructor" << endl;
}
A(const A& x) {
cout << "copy constructor" << endl;
}
const A& operator = (const A& x) {
cout << "operator =" << endl;
return *this;
}
};
int main() {
A a; // default constructor
A b(a); // copy constructor
A c = a; // copy constructor
c = b; // operator =
return 0;
}
``` | Is there a difference between copy-initialization and direct-initialization? | [
"",
"c++",
"initialization",
"copy-initialization",
"direct-initialization",
""
] |
I've just fixed a very subtle bug in our code, caused by slicing of an exception, and I now want to make sure I understand exactly what was happening.
Here's our base exception class, a derived class, and relevant functions:
```
class Exception
{
public:
// construction
Exception(int code, const char* format="", ...);
virtual ~Exception(void);
<snip - get/set routines and print function>
protected:
private:
int mCode; // thrower sets this
char mMessage[Exception::MessageLen]; // thrower says this FIXME: use String
};
class Derived : public Exception {
public:
Derived (const char* throwerSays) : Exception(1, throwerSays) {};
};
void innercall {
<do stuff>
throw Derived("Bad things happened!");
}
void outercall {
try {
innercall();
}
catch(Exception& e)
{
printf("Exception seen here! %s %d\n", __FILE__, __LINE__);
throw e;
}
}
```
The bug was of course that outercall ends up throwing an Exception, instead of a Derived. My bug resulted from higher in the call stack attempts to catch the Derived failing.
Now, I just want to make sure I understand - I believe that at the 'throw e' line, a new Exception object is being created, using a default copy constructor. Is that what's really going on?
If so, am I allowed to lock out copy constructors for objects that will be thrown? I'd really prefer this not happen again, and our code has no reason to copy Exception objects (that I know of).
Please, no comments on the fact that we have our own exception hierarchy. That's a bit of old design that I'm working to correct (I'm making good progress. I've gotten rid of the home-grown string class, and many of the home-grown containers.)
UPDATE: To be clear, I had fixed the bug (by changing 'throw e' to 'throw') before I ever asked the question. I was just looking for confirmation of what was going on. | When you throw an object, you're actually throwing a copy of the object, not the original. Think about it - the original object is on the stack, but the stack is being unwound and invalidated.
I believe this is part of the standard, but I don't have a copy to reference.
The type of exception being thrown in the catch block is the base type of the catch, not the type of the object that was thrown. The way around this problem is to `throw;` rather than `throw e;` which will throw the original caught exception. | [A quick google](http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr153.htm) suggests that yes, you're throwing the copy constructor is required and must be public. (Which makes sense, as you're initializing a copy of `e` and throwing that.)
Anyway, just use `throw` without specifying the exception object, to rethrow what was caught in the `catch`. Shouldn't that solve the problem?
```
catch(Exception& e)
{
printf("Exception seen here! %s %d\n", __FILE__, __LINE__);
throw;
}
``` | Exception slicing - is this due to generated copy constructor? | [
"",
"c++",
"exception",
"object-slicing",
""
] |
I can run a simple "Hello World" Google App Engine application on localhost with no problems. However, when I add the line "import gdata.auth" to my Python script I get "ImportError: No module named gdata.auth".
I have installed the gdata module and added the following line to my .bashrc:
```
export PYTHONPATH=$PYTHONPATH:/Library/Python/2.5/site-packages/
```
Is there anything else I need to do? Thanks.
EDIT: The strange thing is that if I run python from a shell and type "import gdata.auth" I do not get an error. | Your .bashrc is not known to Google App Engine. Make sure the `gdata` directory (with all its proper contents) is under your application's main directory!
See [this article](http://code.google.com/appengine/articles/gdata.html), particularly (and I quote):
> To use this library with your Google
> App Engine application, simply place
> the library source files in your
> application's directory, and import
> them as you usually would. The source
> directories you need to upload with
> your application code are src/gdata
> and src/atom. Then, be sure to call
> the
> `gdata.alt.appengine.run_on_appengine`
> function on each instance of a
> gdata.service.GDataService object.
> There's nothing more to it than that! | The gdata client library installation script installs the modules in the wrong directory for ubuntu python installation.
```
sudo mv /usr/local/lib/python2.6/dist-packages/* /usr/lib/python2.6/dist-packages
``` | Google App Engine cannot find gdata module | [
"",
"python",
"google-app-engine",
"macos",
"gdata",
"google-data-api",
""
] |
How can I change the desktop wallpaper using C# Code? | Here's a class yanked from an app I wrote a year or two ago:
```
public sealed class Wallpaper
{
Wallpaper() { }
const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
public enum Style : int
{
Tiled,
Centered,
Stretched
}
public static void Set(Uri uri, Style style)
{
System.IO.Stream s = new System.Net.WebClient().OpenRead(uri.ToString());
System.Drawing.Image img = System.Drawing.Image.FromStream(s);
string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
if (style == Style.Stretched)
{
key.SetValue(@"WallpaperStyle", 2.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (style == Style.Centered)
{
key.SetValue(@"WallpaperStyle", 1.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (style == Style.Tiled)
{
key.SetValue(@"WallpaperStyle", 1.ToString());
key.SetValue(@"TileWallpaper", 1.ToString());
}
SystemParametersInfo(SPI_SETDESKWALLPAPER,
0,
tempPath,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
}
```
I haven't tested it extensively, so use at your own risk. | Bases on [this useful answer](https://stackoverflow.com/a/1061682/4792350), I've also made [my own app](https://github.com/bad-samaritan/Roller) to set wallpaper matching screen resolution.
But the registry settings were wrong. Here are the correct values (tested on Win 7, Win 8.1, Win 10).
```
if (style == Style.Fill)
{
key.SetValue(@"WallpaperStyle", 10.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (style == Style.Fit)
{
key.SetValue(@"WallpaperStyle", 6.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (style == Style.Span) // Windows 8 or newer only!
{
key.SetValue(@"WallpaperStyle", 22.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (style == Style.Stretch)
{
key.SetValue(@"WallpaperStyle", 2.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (style == Style.Tile)
{
key.SetValue(@"WallpaperStyle", 0.ToString());
key.SetValue(@"TileWallpaper", 1.ToString());
}
if (style == Style.Center)
{
key.SetValue(@"WallpaperStyle", 0.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
``` | Change desktop wallpaper using code in .NET | [
"",
"c#",
".net",
"wpf",
"desktop",
"wallpaper",
""
] |
The size of my JavaScript file is getting out of hand because I have hundreds of links, and each one has its own jQuery function even though they all peform basically the same task.
Here's a short excerpt:
```
$("#link1").click(function ()
{
$(".myDiv").hide();
$("#myDiv1").toggle();
});
$("#link2").click(function ()
{
$(".myDiv").hide();
$("#myDiv2").toggle();
});
$("#link3").click(function ()
{
$(".myDiv").hide();
$("#myDiv3").toggle();
});
```
Would there be a way to abstract some of this logic so that I have only a single function instead of hundreds that do the same thing? | You can add a class to all the links that do the same thing and act with jQuery on that class.
```
<a href='whatever' id='link_1' class='toggler'>text</a>
<a href='whatever' id='link_2' class='toggler'>text</a>
```
jQuery code will be:
```
$(".toggler").click( function(){
// toggle the divs
var number = $(this).attr("id").split('_')[1];
$(".myDiv").hide();
$("#myDiv"+ number).toggle();
});
``` | The general approach that I use is to use the traversal methods to find related elements rather than using absolute selectors. This will allow you to apply the same code to elements that are similarly configured without any complicated dependencies on the format of the ids, etc. Done correctly it's also reasonably robust against minor changes to the mark up.
For example, say I have a series of links, each followed by a div that will be toggled by clicking on that link. The links each have a particular class so they can easily be referenced.
```
<a href="#" class="linkClass">Toggle</a>
<div>
Some content...
</div>
<a href="#" class="linkClass">Toggle</a>
<div>
Other content
</div>
```
I would then find all the links by class, then use the `next` method to find the associated div and toggle it's visibility. Note that this is a simple example. You may need to use more complicated traversal mechanisms and filter by element type or class, too, depending on your exact mark up.
```
$('.linkClass').click( function() {
$(this).next().toggle();
});
``` | How can I reduce the redundancies in my jQuery code? | [
"",
"javascript",
"jquery",
"abstraction",
"redundancy",
""
] |
I'm creating a code that gets image's urls from any web pages, the code are in python and use BeutifulSoup and httplib2.
When I run the code, I get the next error:
```
Look me http://movies.nytimes.com (this line is printed by the code)
Traceback (most recent call last):
File "main.py", line 103, in <module>
visit(initialList,profundidad)
File "main.py", line 98, in visit
visit(dodo[indice], bottom -1)
File "main.py", line 94, in visit
getImages(w)
File "main.py", line 34, in getImages
iSoupList = BeautifulSoup(response, parseOnlyThese=SoupStrainer('img'))
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 226, in parse_starttag
endpos = self.check_for_whole_start_tag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 301, in check_for_whole_start_tag
self.error("malformed start tag")
File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: malformed start tag, at line 942, column 118
```
Someone can explain me how to fix or make an exeption for the error | To catch that error specifically, change your code to look like this:
```
try:
iSoupList = BeautifulSoup(response, parseOnlyThese=SoupStrainer('img'))
except HTMLParseError:
#Do something intelligent here
```
Here's some more reading on Python's try except blocks:
<http://docs.python.org/tutorial/errors.html> | Are you using latest version of BeautifulSoup?
This seems a known issue of version 3.1.x, because it started using a new parser (HTMLParser, instead of SGMLParser) that is much worse at processing malformed HTML. You can find more information about this on [BeautifulSoup website](http://www.crummy.com/software/BeautifulSoup/3.1-problems.html).
As a quick solution, you can simply use an older version ([3.0.7a](http://www.crummy.com/software/BeautifulSoup/download/3.x/BeautifulSoup-3.0.7a.tar.gz)). | how to fix or make an exception for this error | [
"",
"python",
"beautifulsoup",
"httplib2",
""
] |
I ran my code through xdebug profiler and saw more than 30 percent of the time is spent on the require() calls. What is the best way to improve on this? I saw some posts about using \_\_autoload, but there were conflicting statements about it's affect on APC (which we use), and doubts about it's use to improve performance. | The reason why requires consume time is disk IO speed. You can try using autoloading, as you may be requiring files that aren't actually used. Another approach to reduce the disk IO overhead is to combine your PHP files into one large file. Requiring a big file which contains the code you always need is faster than including the same code in multiple small files.
Also, APC has a feature which speeds up requires called apc.include\_once\_override which you can try enabling. | Make sure your includes use absolute instead of relative paths. Easiest way to do this is by prepending your paths with
```
dirname(__FILE__) // for php < 5.3
__DIR__ // for php >= 5.3
``` | PHP performance hampered by require() | [
"",
"php",
"performance",
""
] |
We have a web application that produces reports. Data are taken from a database.
When we ran the web application on a localized system, it blows up. We traced the problem on a DateTime.Parse(dateString); call.
The dates stored in the database is somewhat dependent on the locale of the machine.
On an English system, the date is stored as MM/DD/YYYY (06/25/2009) which is perfectly normal.
On a Russian system, the date is stored as MM.DD.YYYY (06.25.2009). This is weird because the default setting (I checked) for Short Date format in Russian Systems is dd.MM.yyyyy... So it should be 25.06.2009. I don't it get why it accepted the default separator (.) but not the default date format.
So anyway, how can I parse the date string on a localized system? If I use the Russian cultureinfo, it would still throw an error since it is expecting dd.MM.yyyyy.
Thanks! | **You should never store a localized date string in the database.**
You must store dates in date columns and then localize the data at the moment of showing it.
## 1. Set the locale of your site UI
This example set the lang according to the request path, but may have other mechanism.
```
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim lang As String
If HttpContext.Current.Request.Path.Contains("/en/") Then
lang = "en" 'english'
ElseIf HttpContext.Current.Request.Path.Contains("/pt/") Then
lang = "pt" 'portugues'
Else
lang = "es" 'español, the default for the site'
End If
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang)
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang)
End Sub
```
## 2. Get the input to date variables
Getting the data from the text input is easy, this is an example, but with a date validator you should be ok.
```
dim theDate as date
if IsDate( txtDate.text ) then
theDate = DateTime.Parse(txtDate.text)
else
'throw exception or something
end if
```
## Edit
Since you say you can't change the way it is stored, you are in big trouble, unless you have in the db record some way to tell the format of the date. The problem is not the separators, but when you find a date like 6/3/2009 you dont know if it is 6 of march or 3 of june. | At the database, if you **must** store it as text, you should standardize the format. Even better, though, store it as `datetime`, and there is nothing to parse - just read it out from the database as a date...
If you have a string, use the known culture (perhaps the invariant culture) when parsing:
```
DateTime when = DateTime.Parse(s, CultureInfo.InvariantCulture);
``` | Parsing DateTime on Localized Systems | [
"",
"c#",
".net",
"datetime",
""
] |
Given:
* two images of the same subject matter;
* the images have the same resolution, colour depth, and file format;
* the images differ in size and rotation; and
* two lists of (x, y) co-ordinates that correlate the images.
I would like to know:
* **How do you transform the larger image so that it visually aligns to the second image?**
* (Optional.) What are the minimum number of points needed to get an accurate transformation?
* (Optional.) How far apart do the points need to be to get an accurate transformation?
The transformation would need to rotate, scale, and possibly shear the larger image. Essentially, I want to create (or find) a program that does the following:
1. Input two images (e.g., TIFFs).
2. Click several anchor points on the small image.
3. Click the several corresponding anchor points on the large image.
4. Transform the large image such that it maps to the small image by aligning the anchor points.
This would help align pictures of the same stellar object. (For example, a hand-drawn picture from 1855 mapped to a photograph taken by Hubble in 2000.)
Many thanks in advance for any algorithms (preferably Java or similar pseudo-code), ideas or links to related open-source software packages. | This is called [Image Registration](http://en.wikipedia.org/wiki/Image_registration).
[Mathworks](http://www.mathworks.com/access/helpdesk/help/toolbox/images/index.html?/access/helpdesk/help/toolbox/images/f20-14791.html) discusses this, [Matlab](http://www.physiol.ox.ac.uk/Computing/Online_Documentation/Matlab/toolbox/images/images.html) has this ability, and more information is in the [Elastix Manual](http://elastix.isi.uu.nl/download/elastix_manual_v4.1.pdf).
Consider:
* [Open source Matlab equivalents](http://www.wareprise.com/2008/12/13/list-of-matlab-open-source-alternatives/)
* [IRTK](http://www.doc.ic.ac.uk/~dr/software/)
* [IRAF](http://iraf.noao.edu/)
* [Hugin](http://hugin.sourceforge.net/) | you can use the [javax.imageio](http://java.sun.com/j2se/1.4.2/docs/guide/imageio/index.html) or [Java Advanced Imaging](http://java.sun.com/javase/technologies/desktop/media/jai/) api's for rotating, shearing and scaling the images once you found out what you want to do with them. | Auto scale and rotate images | [
"",
"java",
"image-processing",
"transform",
"algorithm",
"image-scaling",
""
] |
I am just beginning to get into desktop application development, and have chosen C# to do so. After making some basic programs, I am wanting to get into more useful creations for myself. I was thinking about making a Project time tracker, as well as a password safe type program of my own. Both of these require taking in information that needs to be stored.
The way I have come across is to use a SQL server for the storage aspect, but from what I have gathered that requires me to have a SQL server installation on all the computers I plan to use these programs with does it not? So I have been leaning towards XML, as it seems to be more mobile and open, but is this a viable option for data storage? And can it be properly encrypted when I get to that step in my password safe program?
Which of these should I begin to implement in my desktop based applications, or is there an alternative I have missed that would be better. | I use [sqlite](http://www.sqlite.org/) for desktop apps that need a good way to store relational information. [Lots of other people](http://www.sqlite.org/famous.html) do too.
SQLite is easy, robust, fast, and light. There are [plenty](http://www.google.com/search?q=sqlite+.NET+provider) of .NET data providers for sqlite, and there's a nice [SQLite browser](http://sqlitebrowser.sourceforge.net/screenshots.html) app to check out your data file.
SQL Server [Express] is appropriate for "big" apps, or apps that need features of a "real" sql database (like stored procedures or something). You can do an [embedded sql server express](http://msdn.microsoft.com/en-us/library/dd981032.aspx), if you have enough memory on your target machines.
XML is appropriate for (read-only) configuration info, but using it as a r/w storage format is just asking for a lot of time in your debugger. | SQL Server is not good at all for desktop applications. However, if you want to use a database instead of XML, you should use [the SQLite](http://www.sqlite.org/) database format, due to not requiring a server, and requires [only a single DLL](http://sqlite.phxsoftware.com/) contining both the DB engine and an ADO.NET driver. | XML or SQL? | [
"",
"c#",
"xml",
"database",
""
] |
I have an idea I'm trying to implement.
I want to display half a dozen pictures on a screen, in say a circle shape, and as I hover over one with the mouse it fades from grey and white into full colour, maybe even getting a little larger, or generating a drop-shadow effect which stays while the mouse is over it.
Although I'm not too shabby on VB6 and SQL Server, my web development experience extends about at far as using notepad to generate raw HTML to display some favourite folders, links to websites and documents etc, in Active Desktop.
So guys, what programming resource websites should I be looking at, such as w3schools.com and specifically whether I should be using JavaScript or some other method ... also specific method calls to look at would be good.
I'm not after "here ... try this code" and then 10 screens of code to cut and paste, I'm after tips, such as "for the positioning, look at [www.thiswebpage.com](http://www.thiswebpage.com) and look at XYZ" and "for the fade effect, look at ABC method on JavaScript" or whatever.
EDIT: 14/07/2009 - Just thought that this might be pertinent. I'll be hosting the pages on a Google Apps hosted website.
Also, the black and white fade effect wasn't the only effect I was considering, it was just one possibility. Other nice, subtle effects might be considered. | What you want to implement shouldn't be all that difficult. However if you do not know any JS then W3C schools is a good place to start.
You should also check out [Mootools](http://mootools.net/). It is a great framework for all your JS needs. They also have some great [demos you can try](http://demos.mootools.net/). | For general effects and starting point for this type of user experience: [JQuery](http://jquery.com/)
From there - research jQuery plugins that do this type of thing. Good search terms may be carousel. | Web page image effects - JavaScript? How else? | [
"",
"javascript",
"css",
"dom-events",
""
] |
I have an iframe window that displays a report. To access this iframe, I have an expand/collapse button on the parent window.
Within the iframe report window, I have a #PAGETOP anchor at the bottom of the report, i,e:
```
<tr><td style="padding-left:45px" class="bottom" colspan="99"><div id="ptAnchor"><a href="#PAGETOP"><img src="first.png" border="1" alt="Top of Page" /></a></div></td></tr>
```
How can I programatically emulate an onclick of this #PAGETOP anchor, when the user presses the "expand" button from the parent window? | The use of `#PAGETOP` anchor is to scroll the window to the top. You can instead write a function to scroll the window to 0,0 coordinates.
```
function ScrollToTop() {
window.scroll(0, 0);
}
```
Put this function in the IFrame, and call it from the parent window. | In the parent doc:
```
<a id="scrollToTop">Expand</a>
<script type="text/javascript">
document.getElementById("scrollToTop").onclick = function(e) {
var childWindow = document.getElementById("theIFrame").contentWindow;
// this should emulate a click on the ptAnchor DIV's child A HREF.
childWindow.document.getElementById("ptAnchor").firstChild.click();
// alternatively, this will simply scroll the child window to the top-left corner
childWindow.scrollTo(0,0);
}
</script>
<iframe id="theIFrame" src="someDocOnTheSameDomain.html"></iframe>
```
Your iframe must be on the same domain for the browser to allow scripting between the parent and child frames.
The **contentWindow** property allows you to access the window object of the child iframe. From there, you can write Javascript to emulate a click or simply scroll the window around. | How can I simulate an anchor click within iframe via JavaScript? | [
"",
"javascript",
""
] |
I'm just getting started with Boost for the first time, details:
1. I'm using Visual Studio 2008 SP1
2. I'm doing an x64 Build
3. I'm using boost::asio only (and any dependencies it has)
My code now compiles, and I pointed my project at the boost libraries (after having built x64 libs) and got past simple issues, now I am facing a linker error:
```
2>BaseWebServer.obj : error LNK2001: unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::get_system_category(void)" (?get_system_category@system@boost@@YAAEBVerror_category@12@XZ)
2>BaseWebServer.obj : error LNK2001: unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::get_generic_category(void)" (?get_generic_category@system@boost@@YAAEBVerror_category@12@XZ)
```
any ideas?
---
I added this define: #define BOOST\_LIB\_DIAGNOSTIC
And now in my output I see this:
```
1>Linking to lib file: libboost_system-vc90-mt-1_38.lib
1>Linking to lib file: libboost_date_time-vc90-mt-1_38.lib
1>Linking to lib file: libboost_regex-vc90-mt-1_38.lib
```
which seems to indicate it is infact linking in the system lib. | I solved the problem. I had built 32-bit libraries when I had intended to build 64-bit libraries. I fixed up my build statement, and built 64-bit libraries, and now it works.
Here is my bjam command line:
```
C:\Program Files (x86)\boost\boost_1_38>bjam --build-dir=c:\boost --build-type=complete --toolset=msvc-9.0 address-model=64 architecture=x86 --with-system
``` | ```
#include <boost/system/config.hpp>
```
In my case, BOOST\_LIB\_DIAGNOSTIC did not show system being automatically linked in. I resolved this by simply including boost/system/config.hpp. | Boost linker error: Unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::get_system_category(void)" | [
"",
"c++",
"windows",
"64-bit",
"boost-asio",
""
] |
I'm a real dummy at UI building, so I'm wondering - what .NET winforms control would be best to use if aiming to display tweets in a list fashion that updates with like boxes which contain the text of the tweet and its metadata below it. Is there a specific winforms list function for this type of thing? Or do you recommend I look for/use a third party winforms control? Thanks! Hope my question wasn't too silly.
**UPDATE**: I am getting indication from numerous responses that it would be better to just build a simple winform control myself, but can anyone point me to a tutorial for doing so? Also, if i were to build such a control, does there exist a convenient built-in control for making like a list of custom controls that is scrollable - maybe Panel? Thanks in advance! | I'd build a user control that would display the information for a single tweet. I'd then repeat that user control in a panel.
You could just use the same layout in your user control that is standard for "tweets".
Left justified picture box to display the user image.
LinkLabel for user name.
Label for tweet text.
**Update**: Here are a couple pages on UserControls
<http://msdn.microsoft.com/en-us/library/a6h7e207(VS.71).aspx>
<http://www.akadia.com/services/dotnet_user_controls.html>
Create a usercontrol using the designer and also a Tweet class that is
just a dumb data structure to hold each tweet's information. Also create a Tweet
property on the custom user control that would handle setting the tweet and assigning information
to the standard controls contained in it (Labels, Textboxs, PictureBox, etc).
In the form where you want to host your user control create a panel that is empty. Somewhere in your code you
would do something similar to this code block.
```
pnlHost.Controls.Clear();
List<Tweet> tweets = new List<Tweet>();
//Populate your collection of tweets here
foreach (Tweet tweet in tweets)
{
TweetControl control = new TweetControl();
control.Tweet = tweet;
pnlHost.Controls.Add(control);
control.Dock = DockStyle.Top;
}
``` | Hi I'd go for a third party grid control from companies like Infragistics, DevExpress or Telerik. Another option would be to build a usercontrol that is able to display one post and put that control into a vb.net repeater control (which ships with the vb.net powerpack). However I'm not sure how good the last solution actually works, as I just read about it, but never tried it. | .NET (C#) winforms "tweet" UI control question | [
"",
"c#",
".net",
"winforms",
"user-interface",
""
] |
I'm working on an application, and I have a screen that in my mind, looks a lot like the Wireless Network List in Windows Vista. For those who are unaware, its basically a listview, but in each row, instead of a line of text, there's a large 'panel' that contains all sorts of useful information. Does anyone know if that's an actual UI control available on windows, or should I roll my own with some sort of autosizing table layout panel hosting a collection of custom controls? | I know this is pretty easy to make using WPF using the stackpanel layout along with a series of user controls containing grid controls for internal layout. Or are you using windows forms? | The wireless network dialog isn't using a standard Win32 control, it's using a custom control (effectively).
If you want to emulate that behavior, you're going to have to use WPF or roll your own. | What C# / Win32 Control Is the Wireless Network Dialog Using? | [
"",
"c#",
"winforms",
"list",
"windows-vista",
"controls",
""
] |
I've created this simple GUI:
```
from tkinter import *
root = Tk()
def grabText(event):
print(entryBox.get())
entryBox = Entry(root, width=60).grid(row=2, column=1, sticky=W)
grabBtn = Button(root, text="Grab")
grabBtn.grid(row=8, column=1)
grabBtn.bind('<Button-1>', grabText)
root.mainloop()
```
When I click on the `Grab` button, an error occurs:
```
C:\Python> python.exe myFiles\testBed.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "myFiles\testBed.py", line 10, in grabText
if entryBox.get().strip()=="":
AttributeError: 'NoneType' object has no attribute 'get'
```
Why is `entryBox` set to `None`?
---
See also [Why do I get AttributeError: 'NoneType' object has no attribute 'something'?](https://stackoverflow.com/questions/8949252) for the general case. | The `grid`, `pack` and `place` functions of the `Entry` object and of all other widgets returns `None`. In python when you do `a().b()`, the result of the expression is whatever `b()` returns, therefore `Entry(...).grid(...)` will return `None`.
You should split that on to two lines like this:
```
entryBox = Entry(root, width=60)
entryBox.grid(row=2, column=1, sticky=W)
```
That way you get your `Entry` reference stored in `entryBox` and it's laid out like you expect. This has a bonus side effect of making your layout easier to understand and maintain if you collect all of your `grid` and/or `pack` statements in blocks. | Change this line:
```
entryBox=Entry(root,width=60).grid(row=2, column=1,sticky=W)
```
into these two lines:
```
entryBox=Entry(root,width=60)
entryBox.grid(row=2, column=1,sticky=W)
```
Just as you already correctly do for `grabBtn`! | Why do I get "AttributeError: NoneType object has no attribute" using Tkinter? Where did the None value come from? | [
"",
"python",
"user-interface",
"tkinter",
""
] |
I use camel case which has the first letter of all variable names, functions, etc lowercased. But the class names are capitalized. Should I use:
```
class Foo
{
function foo()
{
}
}
```
or :
```
class Foo
{
function Foo()
{
}
}
```
Which is a better convention? I'm confused. | Named constructors are PHP 4 convention. And yes, when you do it that way you should match the case of the class.
But PHP 4 is old news these days. PHP 5 has been the de-facto version for several years now. And PHP 5 uses a constant constructor name, \_\_construct. It's always this, regardless of the class' name.
```
class a
{
public function __construct()
{}
}
class b
{
public function __construct()
{}
}
``` | Honestly, neither.
You should be using `__construct()` Unless, of course, you're chained to the rather archaic PHP4, then you exactly match the name of the class. | Should I capitalize constructor names for my classes? | [
"",
"php",
"naming-conventions",
""
] |
Can a C++ compiler produce a not so good binary? You can think here of the output's robustness and performance. Is there such a thing as the "best" C++ compiler to use? If not, what are the strong points, and of course, the not-so-strong (known Bugs and Issues) points, of the well-known compilers (g++, Intel C++ Compiler, Visual C++, etc.).
Are there documented cases when a compiler produced incorrect output which resulted in a failure of mission-critical software? | G++ seems to be the most popular. It's free, portable and quite good. The Windows port (MinGW) was really dated the last time I used it (maybe one year ago).
The Intel C++ compiler is considered as the one which generates the fastest code (however it's known that it generates bad SIMD code for AMD processors).
You can use it freely on GNU/Linux under quite restrictive conditions.
I've used it for some time and I liked the fact that it emits clever warnings which others don't.
VC++ is often regarded as the best C++ IDE, and from what I hear the compiler is quite good too. It's free (as in free beer), and only available on Windows of course.
If you are interested in Windows programming I would suggest this compiler, because it's always up-to-date and provides more advanced features for this purpose.
I would suggest VC++ on Windows, G++ for other OSes. Try the free version of I++ yourself, to see if it's worth the money.
---
> Are there documented cases when a compiler produced incorrect output which resulted in a failure of mission-critical software?
Yes, probably, but I'd say that most of the time it's probably the programmer's fault. For example, if someone doesn't know how floating-point arithmetic works, it's easy to write unreliable code. A good programmer must also know what is guaranteed to work by the C++ standard and what isn't. The programmer should also know what are the limits of the compiler, e.g. how well it implements the standard and how aggressively it optimizes. | Since you mention "as part of a commercial airplane system" in a comment, it may be worthwhile looking at the compilers provided by companies that actually maintain certification in that space, or other safety-critical product spaces. [Green Hills Software](http://www.ghs.com) is one. [Wind River](http://windriver.com/products/development_suite/wind_river_compiler/) is another. | Which is the best C++ compiler? | [
"",
"c++",
"compiler-construction",
"mission-critical",
""
] |
When using a Settings.settings file in .NET, where is the config actually stored?
I want to delete the saved settings to go back to the default state, but can't find where it's stored... any ideas? | It depends on whether the setting you have chosen is at "User" scope or "Application" scope.
### User scope
User scope settings are stored in
```
C:\Documents and Settings\ username \Local Settings\Application Data\ ApplicationName
```
You can read/write them at runtime.
For Vista and Windows 7, folder is
```
C:\Users\ username \AppData\Local\ ApplicationName
```
or
```
C:\Users\ username \AppData\Roaming\ ApplicationName
```
### Application scope
Application scope settings are saved in `AppName.exe.config` and they are readonly at runtime. | Here is the snippet you can use to programmatically get user.config file location:
```
public static string GetDefaultExeConfigPath(ConfigurationUserLevel userLevel)
{
try
{
var UserConfig = ConfigurationManager.OpenExeConfiguration(userLevel);
return UserConfig.FilePath;
}
catch (ConfigurationException e)
{
return e.Filename;
}
}
```
ApplicationSettings (i.e. settings.settings) use PerUserRoamingAndLocal for user settings by default (as I remembered).
**Update:** Strange but there are too many incorrect answers here. If you are looking for you user scoped settings file (user.config) it will be located in the following folder (for Windows XP):
> C:\Documents and
> Settings\(username)\Local
> Settings\Application
> Data\(company-name-if-exists)\(app-name).exe\_(Url|StrongName)\_(hash)\(app-version)\
Url or StrongName depends on have you application assembly strong name or not. | When using a Settings.settings file in .NET, where is the config actually stored? | [
"",
"c#",
".net",
"settings",
""
] |
Can anyone describe the following php function:
```
function get_setting_value($settings_array, $setting_name, $default_value = "")
{
return (is_array($settings_array) && isset($settings_array[$setting_name]) && strlen($settings_array[$setting_name])) ? $settings_array[$setting_name] : $default_value;
}
```
What does it return and whats its purpose? | This is equivalent:
```
function get_setting_value($settings_array, $setting_name, $default_value = "")
{
// Check that settings array really is an array
if (!is_array($settings_array)) {
return $default_value;
}
// Check that the array contains the key $setting_name
if (!isset($settings_array[$setting_name])) {
return $default_value;
}
// Check that the value of that index isn't an empty string
if (!strlen($settings_array[$setting_name])) {
return $default_value;
}
// Return the requested value
return $settings_array[$setting_name];
}
``` | The function returns a setting value if found, or the default value (which is optional).
A more detailed answer:
* if the the given settings array is an actual array
* if the setting\_name exists in the array
* if the setting value represented by the setting name is not empty, false, or 0 then return it
* else return the default value, which, if not set, is an empty string | Can you describe the following PHP function? | [
"",
"php",
"function",
""
] |
I have a very large project with tons of convoluted header files that all include each other. There's also a massive number of third-party libraries that it depends on. I'm trying to straighten out the mess, but I'm having some trouble, since a lot of the time I'll remove one #include directive only to find that the stuff it was including is still included through one of the other files. Is there any tool that can help me understand this? I'd really like to be able to click on a .h file and ask it which CPP files it's included in (directly or indirectly), and the paths through which it is included, and likewise click a cpp file and ask it which .h files are included (directly and indirectly). I've never heard of a tool that does this, and a bit of quick googling hasn't turned anything up, but maybe I don't know what to search for. | <http://www.profactor.co.uk/includemanager.php> | For VS2003 there is /showIncludes flag (in C/C++/Advanced properties). This will print all headers each .cpp file includes and what they include, so you can go from there.
I'm sure there is same option in same place for VS2008. | C++ include file browser | [
"",
"c++",
"include",
"header-files",
""
] |
I'm reading CJ Date's [*SQL and Relational Theory: How to Write Accurate SQL Code*](http://oreilly.com/catalog/9780596523060/), and he makes the case that positional queries are bad — for example, this `INSERT`:
```
INSERT INTO t VALUES (1, 2, 3)
```
Instead, you should use attribute-based queries like this:
```
INSERT INTO t (one, two, three) VALUES (1, 2, 3)
```
Now, I understand that the first query is out of line with the relational model since tuples (rows) are unordered sets of attributes (columns). I'm having trouble understanding where the harm is in the first query. Can someone explain this to me? | The first query breaks pretty much any time the table schema changes. The second query accomodates any schema change that leaves its columns intact and doesn't add defaultless columns.
People who do `SELECT *` queries and then rely on positional notation for extracting the values they're concerned about are [software maintenance supervillains](http://web.archive.org/web/20060515175609/http://codebetter.com/blogs/eric.wise/archive/2005/11/22/134979.aspx) for the same reason. | While the order of columns *is* defined in the schema, it should generally not be regarded as important because it's not *conceptually* important.
Also, it means that anyone reading the first version has to consult the schema to find out what the values are meant to mean. Admittedly this is just like using positional arguments in most programming languages, but somehow SQL feels slightly different in this respect - I'd certainly understand the second version much more easily (assuming the column names are sensible). | Why are positional queries bad? | [
"",
"sql",
"tuples",
"relational-algebra",
"database-relations",
"relational-model",
""
] |
I have a column in my database that is typed `double` and I want to read the value from it using a JDBC ResultSet, but it may be null. What is the best way of doing this? I can think of three options none of which seem very good.
Option 1: Bad because exception handling verbose and smelly
```
double d;
try {
d = rs.getDouble(1);
// do something
} catch(SQLException ex) {
if(rs.wasNull()) {
// do something else
} else {
throw ex;
}
}
```
Option 2: Bad because two fetches
```
s = rs.getString(1); // or getObject()
if(s == null) {
// do something else
} else {
double d = rs.getDouble(1);
// do something
}
```
Option 3: Bad because Java rather than SQL conversion
```
s = rs.getString(1); // or getObject()
if(s == null) {
// do something else
} else {
double d = Double.parseDouble(s);
// do something
}
```
Any suggestions on which way is better, or is there another superior way? And please don't say "Use Hibernate", I'm restricted to JDBC code only here. | Option 1 is closest:
```
double d = rs.getDouble(1);
if (rs.wasNull()) {
// do something
} else {
// use d
}
```
It's not very nice, but that's JDBC. If the column was null, the double value is considered "bad", so you should check using `wasNull()` every time you read a primitive that is nullable in the database. | Depending on your JDBC driver and database, you may be able to use a boxed type and cast:
```
Double doubleValueOrNull = (Double)rs.getObject(1); // or .getObject("columnName")
```
It will be `null` if the column was `NULL`.
Be careful to check this still works if you change database. | How do I in JDBC read a possibly null double value from resultSet? | [
"",
"java",
"jdbc",
"null",
"double",
""
] |
I have some text i need to filter out a list of bad words in like:
```
$bad_words = array(
'word1' => 'gosh',
'word2' => 'darn',
);
```
I can loop through these and replace one at a time but that is slow right? Is there a better way? | Yes there is. Use [`preg_replace_callback()`](https://www.php.net/preg_replace_callback):
```
<?php
header('Content-Type: text/plain');
$text = 'word1 some more words. word2 and some more words';
$text = preg_replace_callback('!\w+!', 'filter_bad_words', $text);
echo $text;
$bad_words = array(
'word1' => 'gosh',
'word2' => 'darn',
);
function filter_bad_words($matches) {
global $bad_words;
$replace = $bad_words[$matches[0]];
return isset($replace) ? $replace : $matches[0];
}
?>
```
That is a simple filter but it has many limitations. Like it won't stop variations on spelling, use of spaces or other non-word characters in between letters, replacement of letters with numbers and so on. But how sophisticated you want it to be is up to you basically.
### UPDATE (9/11/2016)
I realize this is 7 years old, but newer versions of php seem to throw an exception if the word being tested is not in the `$bad_words` array. To fix this, I have changed the last two lines of `filter_bad_words()` as follows:
```
$replace = array_key_exists($matches[0], $bad_words) ? $bad_words[$matches[0]] : false;
return $replace ?: $matches[0];
``` | [str\_ireplace()](https://www.php.net/str_ireplace) can take an array for both search and replace arguments. You can use it with your existing array like this:
```
$unfiltered_string = "gosh and darn are bad words";
$filtered_string = str_ireplace(array_vals($bad_words), array_keys($bad_words), $unfiltered_string);
// $filtered string now contains: "word1 and word2 are bad words"
``` | How do I replace bad words with php? | [
"",
"php",
""
] |
Suppose you have the following situation
```
#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
```
As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal “speak” and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.
But what about Python? Let’s see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:
```
class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
```
Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, there’s no need for this hierarchy. This works equally well
```
class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
```
In Python you can send the signal “speak” to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it won’t compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.
On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...
What I’d like to point out is that I haven’t found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you don’t need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.
So, in the end, the question stands: what's the point of inheritance in Python?
**Edit**: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.
I also found [a similar post](http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html) on this regard. | You are referring to the run-time duck-typing as "overriding" inheritance, however I believe inheritance has its own merits as a design and implementation approach, being an integral part of object oriented design. In my humble opinion, the question of whether you can achieve something otherwise is not very relevant, because actually you could code Python without classes, functions and more, but the question is how well-designed, robust and readable your code will be.
I can give two examples for where inheritance is the right approach in my opinion, I'm sure there are more.
First, if you code wisely, your makeSpeak function may want to validate that its input is indeed an Animal, and not only that "it can speak", in which case the most elegant method would be to use inheritance. Again, you can do it in other ways, but that's the beauty of object oriented design with inheritance - your code will "really" check whether the input is an "animal".
Second, and clearly more straightforward, is Encapsulation - another integral part of object oriented design. This becomes relevant when the ancestor has data members and/or non-abstract methods. Take the following silly example, in which the ancestor has a function (speak\_twice) that invokes a then-abstract function:
```
class Animal(object):
def speak(self):
raise NotImplementedError()
def speak_twice(self):
self.speak()
self.speak()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
```
Assuming `"speak_twice"` is an important feature, you don't want to code it in both Dog and Cat, and I'm sure you can extrapolate this example. Sure, you could implement a Python stand-alone function that will accept some duck-typed object, check whether it has a speak function and invoke it twice, but that's both non-elegant and misses point number 1 (validate it's an Animal). Even worse, and to strengthen the Encapsulation example, what if a member function in the descendant class wanted to use `"speak_twice"`?
It gets even clearer if the ancestor class has a data member, for example `"number_of_legs"` that is used by non-abstract methods in the ancestor like `"print_number_of_legs"`, but is initiated in the descendant class' constructor (e.g. Dog would initialize it with 4 whereas Snake would initialize it with 0).
Again, I'm sure there are endless more examples, but basically every (large enough) software that is based on solid object oriented design will require inheritance. | Inheritance in Python is all about code reuse. Factorize common functionality into a base class, and implement different functionality in the derived classes. | What’s the point of inheritance in Python? | [
"",
"python",
"oop",
"inheritance",
""
] |
As part of a collation changing exercise, I have a list of indexes (122) that needs to be dropped and then re-created. How can I re-create these indexes without having to go through the GUI and scripting it to a query window each time?
My list of indexes is obtained from this script
```
WITH indexCTE AS
(
SELECT Table_Name, Column_Name, Collation_Name
FROM information_schema.columns
WHERE Collation_Name IS NOT NULL AND Collation_Name = 'Modern_Spanish_CI_AS'
),
indexCTE2 AS
(
SELECT i.Name [Index Name], OBJECT_NAME(i.object_ID) [Table Name], c.Name [Column Name]
FROM sys.indexes i
INNER JOIN sys.index_columns ic ON i.index_id = ic.index_id AND i.object_id = ic.object_id
INNER JOIN sys.columns c ON ic.column_id = c.column_id AND ic.object_id = c.OBJECT_ID
WHERE EXISTS (SELECT 1 FROM indexCTE t1 WHERE t1.Table_Name = OBJECT_NAME(i.object_ID) AND t1.Column_Name = c.Name)
) SELECT * FROM indexCTE2
```
As you can probably tell, I'm still a Jr. DBA so please be patient with me!
Thanks! | You're pretty close, I'd say - I tried this, can you verify if this works for you and shows you the expected 122 indices to be recreated??
**UPDATE**: added functionality to determine CLUSTERED vs. NONCLUSTERED index type, and to add INCLUDEd columns to the index definition.
```
WITH indexCTE AS
(
SELECT DISTINCT
i.index_id, i.name, i.object_id
FROM
sys.indexes i
INNER JOIN
sys.index_columns ic
ON i.index_id = ic.index_id AND i.object_id = ic.object_id
WHERE
EXISTS (SELECT * FROM sys.columns c
WHERE c.collation_name = 'Modern_Spanish_CI_AS'
AND c.column_id = ic.column_id AND c.object_id = ic.object_id)
),
indexCTE2 AS
(
SELECT
indexCTE.name 'IndexName',
OBJECT_NAME(indexCTE.object_ID) 'TableName',
CASE indexCTE.index_id
WHEN 1 THEN 'CLUSTERED'
ELSE 'NONCLUSTERED'
END AS 'IndexType',
(SELECT DISTINCT c.name + ','
FROM
sys.columns c
INNER JOIN
sys.index_columns ic
ON c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 0
WHERE
indexCTE.OBJECT_ID = ic.object_id
AND indexCTE.index_id = ic.index_id
FOR XML PATH('')
) ixcols,
ISNULL(
(SELECT DISTINCT c.name + ','
FROM
sys.columns c
INNER JOIN
sys.index_columns ic
ON c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 1
WHERE
indexCTE.OBJECT_ID = ic.object_id
AND indexCTE.index_id = ic.index_id
FOR XML PATH('')
), '') includedcols
FROM
indexCTE
)
SELECT
'CREATE ' + IndexType + ' INDEX ' + IndexName + ' ON ' + TableName +
'(' + SUBSTRING(ixcols, 1, LEN(ixcols)-1) +
CASE LEN(includedcols)
WHEN 0 THEN ')'
ELSE ') INCLUDE (' + SUBSTRING(includedcols, 1, LEN(includedcols)-1) + ')'
END
FROM
indexCTE2
ORDER BY
TableName, IndexName
```
Do you get the `CREATE INDEX` statements you're looking for??
Marc | Great script Marc.
The only thing I think it is missing is the ascending or descending order indicator on each column. I have amended your script to include a case statement for the indexed columns to add in ASC or DESC depending on the is\_descending\_key column of the sys.index\_columns view.
```
WITH indexCTE AS
(
SELECT DISTINCT
i.index_id, i.name, i.object_id
FROM
sys.indexes i
INNER JOIN
sys.index_columns ic
ON i.index_id = ic.index_id AND i.object_id = ic.object_id
WHERE
EXISTS (SELECT * FROM sys.columns c
WHERE
c.collation_name = 'Modern_Spanish_CI_AS'
AND c.column_id = ic.column_id AND c.object_id = ic.object_id)
),
indexCTE2 AS
(
SELECT
indexCTE.name 'IndexName',
OBJECT_NAME(indexCTE.object_ID) 'TableName',
CASE indexCTE.index_id
WHEN 1 THEN 'CLUSTERED'
ELSE 'NONCLUSTERED'
END AS 'IndexType',
(SELECT CASE WHEN ic.is_descending_key = 1 THEN c.name + ' DESC ,'
ELSE c.name + ' ASC ,'
END
FROM
sys.columns c
INNER JOIN
sys.index_columns ic
ON c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 0
WHERE
indexCTE.OBJECT_ID = ic.object_id
AND indexCTE.index_id = ic.index_id
FOR XML PATH('')
) ixcols,
ISNULL(
(SELECT DISTINCT c.name + ','
FROM
sys.columns c
INNER JOIN
sys.index_columns ic
ON c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 1
WHERE
indexCTE.OBJECT_ID = ic.object_id
AND indexCTE.index_id = ic.index_id
FOR XML PATH('')
), '') includedcols
FROM
indexCTE
)
SELECT
'CREATE ' + IndexType + ' INDEX ' + IndexName + ' ON ' + TableName +
'(' + SUBSTRING(ixcols, 1, LEN(ixcols)-1) +
CASE LEN(includedcols)
WHEN 0 THEN ')'
ELSE ') INCLUDE (' + SUBSTRING(includedcols, 1, LEN(includedcols)-1) + ')'
END
FROM
indexCTE2
ORDER BY
TableName, IndexName
``` | Generate CREATE scripts for a list of indexes | [
"",
"sql",
"sql-server-2005",
""
] |
I'm working with a web service that will give me values like:
```
var text = "<<<&&&";
```
And i need to print this to look like "<<<&&&" with javascript.
But here's the catch: i can't use inner HTML(I'm actually sending this values to a prototype library that creates Text Nodes so it doesn't unescape my raw html string. If editing the library would not be an option, how would you unescape this html?
I need to undertand the real deal here, what's the risk of unescaping this type of strings? how does innerHTML does it? and what other options exist?
**EDIT**- The problem is not about using javascript normal escape/unescape or even jQuery/prototype implementations of them, but about the security issues that could come from using any of this... aka "They told me it was pretty insecure to use them"
(For those trying to undertand what the heck im talking about with innerHTML unescaping this weird string, check out this simple example:
```
<html>
<head>
<title>createTextNode example</title>
<script type="text/javascript">
var text = "<<<&&&";
function addTextNode(){
var newtext = document.createTextNode(text);
var para = document.getElementById("p1");
para.appendChild(newtext);
}
function innerHTMLTest(){
var para = document.getElementById("p1");
para.innerHTML = text;
}
</script>
</head>
<body>
<div style="border: 1px solid red">
<p id="p1">First line of paragraph.<br /></p>
</div><br />
<button onclick="addTextNode();">add another textNode.</button>
<button onclick="innerHTMLTest();">test innerHTML.</button>
</body>
</html>
``` | Change your test string to `<b><<&&&</b>` to get a better handle on what the risk is... (or better, `<img src='http://www.spam.com/ASSETS/0EE75B480E5B450F807117E06219CDA6/spamReg.png' onload='alert(document.cookie);'>` for cookie-stealing spam)
See the example at <http://jsbin.com/uveme/139/> (based on your example, using prototype for the unescaping.) Try clicking the four different buttons to see the different effects. Only the last one is a security risk. (You can view/edit the source at <http://jsbin.com/uveme/139/edit>) The example doesn't actually steal your cookies...
1. If your text is coming from a known-safe source and is ***not based on any user input***, then you are safe.
2. If you are using `createTextNode` to create a text node ***and `appendChild` to insert that unaltered node object directly into your document***, you are safe.
3. Otherwise, you need to take appropriate measures to ensure that unsafe content can't make it to your viewer's browser.
Note: [As pointed out by Ben Vinegar](http://benv.ca/2012/10/2/you-are-probably-misusing-DOM-text-methods/) Using `createTextNode` is not a magic bullet: using it to escape the string, then using `textContent` or `innerHTML` to get the escaped text out and doing other stuff with it does not protect you in your subsequent uses. In particluar, the [escapeHtml method in Peter Brown's answer below](https://stackoverflow.com/a/12739170) is insecure if used to populate attributes. | A very good read is <http://benv.ca/2012/10/4/you-are-probably-misusing-DOM-text-methods/> which explains why the convention wisdom of using createTextNode is actually not secure at all.
A representative example take from the article above of the risk:
```
function escapeHtml(str) {
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
};
var userWebsite = '" onmouseover="alert(\'derp\')" "';
var profileLink = '<a href="' + escapeHtml(userWebsite) + '">Bob</a>';
var div = document.getElementById('target');
div.innerHtml = profileLink;
// <a href="" onmouseover="alert('derp')" "">Bob</a>
``` | How to unescape html in javascript? | [
"",
"javascript",
"html",
"escaping",
""
] |
Two quotes:
> All of the remaining messages in the protocol take the form of `<length prefix><message ID><payload>`. The length prefix is a four byte big-endian value. The message ID is a single decimal byte. The payload is message dependent.
>
> ```
> request: <len=0013><id=6><index><begin><length>
> ```
>
> The request message is fixed length, and is used to request a block.
> The payload contains the following information:
>
> * index: integer specifying the zero-based piece index
> * begin: integer specifying the zero-based byte offset within the piece
> * length: integer specifying the requested length.
When I write everything it sums up to 5 bytes. Using
```
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byteStream.write( 13 );
byteStream.write( 6 );
byteStream.write( index );
byteStream.write( begin );
byteStream.write( length );
message = byteStream.toByteArray();
```
EDIT: Sorry i was kind of pissed when i wrote it. its the bittorent protocol.
Using this [spec](http://wiki.theory.org/BitTorrentSpecification#Peer_wire_protocol_.28TCP.29). | The write() method writes one byte.
If you send it a char or int it just strips everything above the 8th bit with & 0xFF.
You have more options with DataOutputStream (writeInt, writeShort etc.) but it uses big endian byte order so you might need to perform an Integer.reverseBytes() (or Short.reverseBytes()) call before passing in the value to the writeXYZ() method.
```
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(byteStream);
dout.writeInt( 0x13 ); // L:4
dout.write( 6 ); // L:5
dout.writeShort( index ); // guess, L:7
dout.writeLong( begin ); // >4GB support? L:15
dout.writeInt( length ); // clients accept below to 2^17, L:19
dout.flush(); // to be sure
message = byteStream.toByteArray();
```
Remark: The spec doesn't state the length of `index`, `begin` and `length`. I just wanted to give a sample of the available options.
**Edit 2:** Edited the sample based on D.Shawley's answer and a spec found [here](http://www.bittorrent.org/beps/bep_0003.html#all-non-keepalive-messages-start-with-a-single-byte-which-gives-their-type). | I'm not sure what you are getting at here... the quoted text doesn't say what the length of `<index>`, `<begin>`, or `<length>` is. The first quote states, rather clearly, that a message consists of a 4-byte length, followed by a 1-byte identifier, and an arbitrary payload.
The length of the payload is probably either the value specified as `<length>` or `<length>`+5 depending on exactly what `<length>` means. The second quote looks like the definition of whatever message is identified by the 1-byte identifier of 0x06. I would guess that:
1. the payload, the bytes that make up `<index><begin><length>`, is probably 14 bytes long
2. the length is being displayed in hex so 0x0013 is 19 decimal
In any case, the byte stream that you are generating does not seem to match the message definition **AND** the message definition lacks clarity. | How is this 13 bytes long? | [
"",
"java",
"byte",
"bytearrayoutputstream",
""
] |
I'm new to web development, so I apologize if this question is noobish. I want to serve a file that is on the server's hard drive to the user when requested (ie, send an HTTP attachment to trigger the browser's "Save as..." dialog) in Javascript. The user clicks on a button on the page, the server generates a customized data file based on some of his/her account settings (and other parameters), and then the "Save as..." dialog should pop up. How should I go about implementing this in Javascript?
**edit:** for your reference, the server has Glassfish and Apache | Jane,
The save-as dialog only appears on page load. You need to redirect your user either directly to the file you want them to save, or to a server-side page that serves up the file.
Once you know the address of the file, do something like
```
window.location = http://yourserver.com/generatedfiles/file_2342342.txt
```
Alternatively, do something like this:
```
window.location = http://yourserver.com/getgeneratedfile.aspx?fileID=2342342
```
...which would redirect the user to a page that feeds the generated file. You then need to specify the content-disposition and filename in the header that comes from that page, as mentioned in Gandalf's reply.
**Edit:** Ah, you're using Apache. Probably won't have ASPX files on there then. | Set the Http Response header:
```
Content-Disposition: attachment; filename=myfile.txt
```
Or something like this
```
<a href="javascript:void(0);" onclick="document.execCommand('SaveAs',true,'file.html');">Save this page</a>
``` | Using Javascript to send an HTTP attachment to the user (open browser's Save as... dialog) | [
"",
"javascript",
"download",
""
] |
I've created this regex
```
(www|http://)[^ ]+
```
that match every *http://...* or *www....* but I dont know how to make preg\_replace that would work, I've tried
```
preg_replace('/((www|http://)[^ ]+)/', '<a href="\1">\1</a>', $str);
```
but it doesn't work, the result is empty string. | You need to escape the slashes in the regex because you are using slashes as the delimiter. You could also use another symbol as the delimiter.
```
// escaped
preg_replace('/((www|http:\/\/)[^ ]+)/', '<a href="\1">\1</a>', $str);
// another delimiter, '@'
preg_replace('@((www|http://)[^ ]+)@', '<a href="\1">\1</a>', $str);
``` | When using the regex codes provided by the other users, be sure to add the "i" flag to enable case-insensitivity, so it'll work with both HTTP:// and http://. For example, using chaos's code:
```
preg_replace('!(www|http://[^ ]+)!i', '<a href="\1">\1</a>', $str);
``` | How to replace http:// or www with <a href.. in PHP | [
"",
"php",
"regex",
"preg-replace",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.