Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a user control that I'm building. It's purpose is to display the status of a class to the user. Obviously, this does not matter, and will slow things down when the control runs in the IDE, as it does as soon as you add it to a form.
One way to work around this would be to have the control created and added to t... | ```
public static bool IsInRuntimeMode( IComponent component ) {
bool ret = IsInDesignMode( component );
return !ret;
}
public static bool IsInDesignMode( IComponent component ) {
bool ret = false;
if ( null != component ) {
ISite site = component.Site;
if ( null != site ) {
... | I found this answer on another post and it seems to be easier and working better for my situation.
[Detecting design mode from a Control's constructor](https://stackoverflow.com/questions/1166226/detecting-design-mode-from-a-controls-constructor)
```
using System.ComponentModel;
if (LicenseManager.UsageMode == Licen... | How can I detect whether a user control is running in the IDE, in debug mode, or in the released EXE? | [
"",
"c#",
"ide",
"user-controls",
""
] |
I have put together a script which is very much like the flickr photostream feature. Two thumbnails next to each other, and when you click the next or prev links the next (or previous) two images slide in. Cool!
Currently when the page loads it loads the two images. The first time nxt / prv is used then the next two i... | To preload an image from Javascript, you don't need to do anything that sounds like AJAX or JSON. All you need is this:
```
var img = new Image();
img.src = "http://example.com/new/image.jpg";
```
The browser will quite happily load the image in the background, even though it's not displayed anywhere. Then, when you ... | Fetching JSON Via Ajax will just slow you down.
You're better off using inline JSON and generated Javascript.
```
<?php
$images = array( "foo.jpg","bar.jpg" );
?>
<script type="text/javascript">
jQuery(function($){
var images = ( <?php echo json_encode($images); ?> );
/* Creating A Hidde... | php/Ajax - Best practice for pre-loading images | [
"",
"php",
"ajax",
"json",
"performance",
"loading",
""
] |
Is it possible to create a multithreading application in VC6 with boost library?
If it is possible, what are some relevant tutorials. | Yes, I have done this successfully, but with Boost v1.30.0. So if you have trouble with the latest versions of the Boost libraries, you might want to go back a year or five. I recall I started getting all sorts of internal compiler errors, *et al.*, when trying to upgrade Boost -- so I didn't, but rather went on using ... | <http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html> | Creating a multithreading application in vc6 with boost library? | [
"",
"c++",
"visual-c++-6",
"boost-thread",
""
] |
Is it possible, or does anyone know the best way to capture MSN chats? I was thinking about attaching to the MSN process, and messing about searching for static addresses for conversations, to capture them.
(This is all on the windows platform using c++) | It would probably be easiest to sniff packets on the ports known to be used by MSN. That has the added benefit of working with clients other than the Microsoft one (such as Pidgin). | Assuming the protocol is unencrypted, it would probably be easier to attach to the process and intercept the network traffic than to search all of the application memory for chats. But that's no small task, either. | Capturing MSN Chat via Memory | [
"",
"c++",
"chat",
"capture",
"msn",
""
] |
I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?
**UPDATE**
This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?
I sent Guido... | **`math.sqrt(x)` is significantly faster than `x**0.5`.**
```
import math
N = 1000000
```
```
%%timeit
for i in range(N):
z=i**.5
```
> 10 loops, best of 3: 156 ms per loop
```
%%timeit
for i in range(N):
z=math.sqrt(i)
```
> 10 loops, best of 3: 91.1 ms per loop
Using Python 3.6.9 ([notebook](https://col... | * first rule of optimization: *don't do it*
* second rule: *don't do it*, yet
Here's some timings (Python 2.5.2, Windows):
```
$ python -mtimeit -s"from math import sqrt; x = 123" "x**.5"
1000000 loops, best of 3: 0.445 usec per loop
$ python -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)"
1000000 loops, best ... | Which is faster in Python: x**.5 or math.sqrt(x)? | [
"",
"python",
"performance",
""
] |
What would be the best way to display & program simple game board (say chess, checkers and such) in C#? In terms of controls and underlying game logic.
An idea that came to my mind was to use **Picture Box** (or class inheriting from it) with Board & Field classes.
* Is that a decent solution after all?
* How would I... | In an object-oriented approach, think about the objects involved in your game (e.g. the board, the pieces) … let them each provide a drawing method that takes a `Graphics` object and draws itself on it.
The drawing itself could be done on a `PictureBox` – this is the ideal control for such purpose – but this isn't rea... | From data structure perspective take a look at the bitboard datastructure. <http://en.wikipedia.org/wiki/Bitboard> | Best way to display & program game board? | [
"",
"c#",
""
] |
I'm trying to figure out if there's a reasonably efficient way to perform a lookup in a dictionary (or a hash, or a map, or whatever your favorite language calls it) where the keys are regular expressions and strings are looked up against the set of keys. For example (in Python syntax):
```
>>> regex_dict = { re.compi... | What you want to do is very similar to what is supported by xrdb. They only support a fairly minimal notion of globbing however.
Internally you can implement a larger family of regular languages than theirs by storing your regular expressions as a character trie.
* single characters just become trie nodes.
* .'s beco... | This is definitely possible, as long as you're using 'real' regular expressions. A textbook regular expression is something that can be recognized by a [deterministic finite state machine](http://en.wikipedia.org/wiki/Deterministic_finite_state_machine), which primarily means you can't have back-references in there.
T... | Hashtable/dictionary/map lookup with regular expressions | [
"",
"python",
"regex",
"dictionary",
"hash",
""
] |
I'd like to create a popup dialog box in silverlight in which i can manipulate controls, enter data, and return a value. I want it to be modal, so that when it is open, the page "Below" is inaccessible. I havent found an easy way to do this yet. Any suggestions? | I know the question asked for a Silverlight 2 solution but in Silverlight 3 (Beta now, RTW in July 2009) there is a built-in ChildWindow that can do everything you're looking for. | I haven't found a perfect solution either. The closest I have seen is this:
[Using Popup to create a Dialog class](http://blogs.msdn.com/devdave/archive/2008/06/08/using-popup-to-create-a-dialog-class.aspx)
If it is ok to be non-modal, you can try this tip using HtmlPage.PopupWindow().
[How to Popup a Browser Window](... | How do I create a Popup Dialog box in Silverlight? | [
"",
"c#",
".net",
"silverlight",
"silverlight-2.0",
""
] |
Published Date returned from Twitter Search API Atom Feed as 2008-11-03T21:30:06Z which needs to be converted to "X seconds/minutes/hours/days ago" for showing how long ago twitter messages were posted.
Think this can be done with php date() function using DATE\_ATOM value? | ```
function time_since($your_timestamp) {
$unix_timestamp = strtotime($your_timestamp);
$seconds = time() - $unix_timestamp;
$minutes = 0;
$hours = 0;
$days = 0;
$weeks = 0;
$months = 0;
$years = 0;
if ( $seconds == 0 ) $seconds = 1;
if ( $seconds> 60 ) {
$minutes = $se... | [strtotime](https://www.php.net/strtotime) will handle that date format, giving you a unix timestamp. You can then follow the algorithms on [How do I calculate relative time?](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time) to get your result. | PHP Convert HTML Formatted Date | [
"",
"php",
"date",
"atom-feed",
""
] |
How can I create a regex for a string such as this:
```
<SERVER> <SERVERKEY> <COMMAND> <FOLDERPATH> <RETENTION> <TRANSFERMODE> <OUTPUTPATH> <LOGTO> <OPTIONAL-MAXSIZE> <OPTIONAL-OFFSET>
```
Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also b... | Just splitting on whitespace is never going to work. But if you can make some assumptions on the data it could be made to work.
Some assumptions I had in mind:
* `SERVER`, `SERVERKEY` and `COMMAND` not containing any spaces: `\S+`
* `FOLDERPATH` beginning with a slash: `/.*?`
* `RETENTION` being a number: `\d+`
* `TR... | The problem is that because you're allowing spaces in filenames and using spaces to separate fields, the solution is ambiguous. You either need to use a different field separator character that can't appear in filenames, or use some other method of representing filenames with spaces in them, e.g. putting them in quotat... | How do I process a string such as this using regular expressions? | [
"",
"python",
"regex",
""
] |
I've got to write few words about C#, generally piece of cake? No!
I've searched through various internet resources and books and what i got is kind of headache. For example **Garbage Collector** some sources says that this is C# feature, other that CLR got this feature and C# along with all other .NET languages got i... | GC is provided by the CLR
C# is everything that the language spec states, and no more.
Some of the more-interesting things that are actually C# features:
* iterator blocks [yield return]
* anonymous methods / closures / lambdas [the syntax, not to be confused with expression trees]
But anything that relates to the ... | The GC itself is a CLR feature, but the C# language assumes that it's running on a platform with garbage collection - without defining the exact semantics.
It's a tough thing to pin down precisely, but a rough rule of thumb is "if it's well defined in the language specification, it's a C# feature."
If you could give ... | C# and CLR features confusion, what feature deserves to be described strictly as C# feature? | [
"",
"c#",
".net",
"clr",
""
] |
I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.
```
<img src="pic.jpg" usemap="#picmap" />
<map id="picmap" name="picmap"><area shape="rect" coords ="10,20,30,40"
onMouseOver="mouse_on_write('mouse is on spot')"
onMouseOut="mous... | You don't need to create any page elements, it can all be preloaded using JavaScript:
```
tempImg = new Image()
tempImg.src="pic2.jpg"
```
EDIT:
If you have a lot of images, you can use the poor-man's multi-preloader:
```
preloads = "red.gif,green.gif,blue.gif".split(",")
var tempImg = []
for(var x=0;x<preloads.le... | Doing this with sprites is a good solution, because you don't have to wait to load the new image. Sprites work by combining the two images into one, and changing the background offset on mouseover.
You can even do with with CSS instead, for much faster results. There's a good tutorial on this [here](http://www.alistap... | How do I pre-cache images for quick viewing with javascript? | [
"",
"javascript",
"html",
""
] |
I need to get a file from sourcesafe database programmatically. Any idea of how to do it?
ps: I'll do that by using C#. | ```
using System;
using System.Collections.Generic;
using SourceSafeTypeLib;
namespace YourNamespace
{
public class SourceSafeDatabase
{
private readonly string dbPath;
private readonly string password;
private readonly string rootProject;
private readonly string username;
private readonly VSSDat... | There is a command-line SS.EXE program that you can call to do source control operations. However, it relies on global SourceSafe configuration and so it sometimes is hard to make it do what you want. | How to get a file from sourcesafe programmatically? | [
"",
"c#",
"visual-sourcesafe",
""
] |
We are considering switching from MS Visual Studio 2003 to MS Visual Studio 2005 for our C++ development. I think jumping to 2008 might be better.
In what ways are VS2008 better than VS2005 for C++ development?
Are there any disadvantages of VS2008 over VS2005? | There are very little difference between 2005 and 2008 from native C++ developer point of view. However, if coming from 2003, it makes sense to upgrade directly to 2008 - the conversion process should be almost the same, and you will end up with a slightly better platform. Some new features which are available for 2008... | To be honest, as far as pure C++ development goes, I don't think there is much between the two, other than VS2008 is the 'latest' release. I didn't notice any significant changes.
However, the latest release of MFC has been given a new lease of life with the addition of the Feature Pack (giving you an MSOffice 2007 lo... | What are the advantages of VS2008 over VS2005 for C++ development? | [
"",
"c++",
"visual-studio-2008",
"visual-studio-2005",
""
] |
I found this in the code I'm working on at the moment and thought it was the cause of some problems I'm having.
In a header somewhere:
```
enum SpecificIndexes{
//snip
INVALID_INDEX = -1
};
```
Then later - initialization:
```
nextIndex = INVALID_INDEX;
```
and use
```
if(nextIndex != INVALID_INDEX)
{
... | Yes to everything.
It is valid code, it is also commonly used library-side C++ code, more so in modern C++ (it is strange when you see it the first time but its a very common pattern in reality).
Then enums are signed ints, but they get implicitly cast into unsigned ints, now this depending on your compiler might give... | enums may be represented by signed or unsigned integral types according to whether they contain any negative values and what the compiler feels like. The example here contains a negative value and hence must be represented by a signed integral type.
Equality comparison between signed and unsigned types is safe and usu... | C++ enum to unsigned int comparison | [
"",
"c++",
"enums",
"comparison",
"integer",
"unsigned",
""
] |
I've got a couple django models that look like this:
```
from django.contrib.sites.models import Site
class Photo(models.Model):
title = models.CharField(max_length=100)
site = models.ForeignKey(Site)
file = models.ImageField(upload_to=get_site_profile_path)
def __unicode__(self):
return sel... | I would delete `site` field on my `Photo` model and add a `ForeignKey` to `Gallery`. I would remove `limit_choices_to` from `photos` fields on `Gallery` model.
Because you are using `ForeignKey`s to `Site`s, that means sites don't share galleries and photos. Therefore having those I mentioned above is already useless.... | Yes. You need to override the form that admin uses for the `Gallery` model, then limit the queryset of the `photos` field in that form:
```
class GalleryAdminForm(django.forms.ModelForm):
class Meta:
model = Gallery
def __init__(self, *args, **kwargs):
super(GalleryAdminForm, self).__init__(*... | Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model? | [
"",
"python",
"django",
"foreign-keys",
"manytomanyfield",
"limit-choices-to",
""
] |
I have a particular PHP page that, for various reasons, needs to save ~200 fields to a database. These are 200 separate insert and/or update statements. Now the obvious thing to do is reduce this number but, like I said, for reasons I won't bother going into I can't do this.
I wasn't expecting this problem. Selects se... | You should be able to do 200 inserts relatively quickly, but it will depend on lots of factors. If you are using a transactional engine and doing each one in its own transaction, don't - that creates way too much I/O.
If you are using a non-transactional engine, it's a bit trickier. Using a single multi-row insert is ... | mysql\_query('INSERT INTO tableName VALUES(...),(...),(...),(...)')
Above given query statement is better. But we have another solution to improve the performance of insert statement.
Follow the following steps..
1. You just create a csv(comma separated delimited file)or simple txt file and write all the data that... | How to implement background/asynchronous write-behind caching in PHP? | [
"",
"php",
"mysql",
"caching",
""
] |
I am trying to convert this test code to C# and having a problem with the Trim command. Has anyone done anything similiar like this in C# going to use this with a text box for searching the aspx page.
```
Dim q = From b In db.Blogs _
Where b.BlogContents.Contains(txtSearch.Text.Trim()) Or _
b.Blo... | What is the issue you are having? And what LINQ provider is this? An in-memory set (LINQ-to-Objects)? Or LINQ-to-SQL? Or LINQ-to-Entities?
I *suspect* you are getting something about the db LINQ provider not knowing about Trim() - in which case, try doing the trim first:
```
string s = txtSearch.Text.Trim();
var q = ... | not sure what you are asking but the Trim function in c# is the same.
<http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx> | Using Linq and the Trim.Text for Search | [
"",
"c#",
"linq",
""
] |
I am working on a plugin system that loads .dll's contained in a specified folder. I am then using reflection to load the assemblies, iterate through the types they contain and identify any that implement my `IPlugin` interface.
I am checking this with code similar to the following:
```
foreach(Type t in myTypes )
{
... | That typically happens when there's a mismatch between the assembly which contains the type IPlugin that the current assembly references, and the assembly which is referenced by the assembly containg the types you're iterating over.
I suggest you print:
```
typeof (IPlugin).Module.FullyQualifiedName
```
and
```
for... | I had same issue when interface was defined in a separate assembly to implementing type.
Iterating and loading assemblies from root folder that contained dlls with classes AND dll with interface resulted in type mismatch as mentioned above.
One solution was to change `LoadFrom()` to `LoadFile()`
The `LoadFrom` method ... | IsAssignableFrom() returns false when it should return true | [
"",
"c#",
".net",
"reflection",
""
] |
I'm using Java 1.5 and I'd like to launch the associated application to open the file. I know that Java 1.6 introduced the [Desktop API](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/), but I need a solution for **Java 1.5**.
So far I found a way to do it in Windows:
```
Runtime.get... | +1 for [this answer](https://stackoverflow.com/questions/325299/#325517)
Additionally I would suggest the following implementation using polymorphism:
This way you can add new platform easier by reducing coupling among classes.
*The Client code:*
```
Desktop desktop = Desktop.getDesktop();
desktop.open( aFile );... | ```
public static boolean isWindows() {
String os = System.getProperty("os.name").toLowerCase();
return os.indexOf("windows") != -1 || os.indexOf("nt") != -1;
}
public static boolean isMac() {
String os = System.getProperty("os.name").toLowerCase();
return os.indexOf("mac") != -1;
}
public static boolea... | Cross-platform way to open a file using Java 1.5 | [
"",
"java",
"linux",
"file-association",
"java-5",
""
] |
Is there a way in MySQL to select rows which fall on a specific day, as in Mondays, using a date column? | MySQL [DAYOFWEEK](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_dayofweek) function.
E.g. to select Mondays:
```
SELECT * FROM foo WHERE DAYOFWEEK(bar) = 2
``` | Look up the DAYOFWEEK() function [here](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_dayofweek) in the MySQL Online Docs | Way to select rows which fall on a specific day? | [
"",
"sql",
"mysql",
""
] |
I am creating my textbox with these options. I can Copy / Cut / Paste / Undo, but when I hit **Select All** it doesn't select all. I can right click and click **Select All** but `CTRL` + `A` doesn't do anything. Why?
```
wnd = CreateWindow("EDIT", 0,
WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL |... | I tend to use MFC (forgive me) instead of Win32 so I cannot answer this definitively, but I noticed this comment added to a page on an MS site concerning talking with an Edit control (a simple editor within the Edit control):
> The edit control uses `WM_CHAR` for
> accepting characters, not `WM_KEYDOWN`
> etc. You mus... | `Ctrl`+`A` is not a built-in accelerator like `Ctrl`+`C` and `Ctrl`+`V`. This is why you see WM\_CUT, WM\_PASTE and WM\_COPY messages defined, but there is no WM\_SELECTALL.
You have to implement this functionality yourself. I did in my MFC app like this:
```
static BOOL IsEdit( CWnd *pWnd )
{
if ( ! pWnd ) retu... | win32 select all on edit ctrl (textbox) | [
"",
"c++",
"user-interface",
"winapi",
"textbox",
""
] |
Suppose I have code like this:
```
template<class T, T initial_t> class Bar {
// something
}
```
And then try to use it like this:
```
Bar<Foo*, NULL> foo_and_bar_whatever_it_means_;
```
GCC bails out with error (on the above line):
> could not convert template argument
> '0' to 'Foo\*'
I found this thread: <ht... | Rethinking your code is probably the best way to get around it. The thread you linked to includes a clear quote from the standard indicating that this isn't allowed. | To accept `Bar<Foo, NULL>`, you need
```
template <typename T, int dummy> class Bar; /* Declared but not defined */
template <typename T> class Bar <T,NULL> { /* Specialization */ };
```
since typeof(NULL)==int. | How to overcome GCC restriction "could not convert template argument '0' to 'Foo*'"? | [
"",
"c++",
"templates",
"gcc",
""
] |
I'm trying to implement a `KeyListener` for my `JFrame`. On the constructor, I'm using this code:
```
System.out.println("test");
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) { System.out.println( "tester"); }
public void keyReleased(KeyEvent e) { System.out.println("2test2"); }
... | You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.
The process is the same:
```
myComponent.addKeyListe... | If you don't want to register a listener on every component,
you could **add your own `KeyEventDispatcher`** to the `KeyboardFocusManager`:
```
public class MyFrame extends JFrame {
private class MyDispatcher implements KeyEventDispatcher {
@Override
public boolean dispatchKeyEvent(KeyEvent e... | Unresponsive KeyListener for JFrame | [
"",
"java",
"swing",
"jframe",
"keylistener",
""
] |
I have two tables with the same columns, and I need to copy one table's rows to the other table's rows to create one big table with all the values from both tables. Right now I am doing this query to return the same thing:
```
SELECT col1, col2, col3 from Table1
union
SELECT col1, col2, col3 from Table2
```
However, ... | May it work to just do:
```
SELECT col1, col2, col3
INTO Table1
FROM Table2
``` | Start with union all:
```
select col1, col2, col3 from Table1
union all
select col1, col2, col3 from Table2
```
Your query is trying to deduplicate things, which would slow it down considerably. | join two tables into one big table | [
"",
"sql",
"database",
""
] |
I have a [`JPanel`](http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JPanel.html) to which I'd like to add JPEG and PNG images that I generate on the fly.
All the examples I've seen so far in the [Swing Tutorials](http://java.sun.com/docs/books/tutorial/uiswing/), specially in the [Swing examples](http://j... | Here's how I do it (with a little more info on how to load an image):
```
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public cla... | If you are using JPanels, then are probably working with Swing. Try this:
```
BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
add(picLabel);
```
The image is now a swing component. It becomes subject to layout conditions like any other componen... | How to add an image to a JPanel? | [
"",
"java",
"image",
"swing",
"jpanel",
""
] |
I have input consisting of a list of nested lists like this:
```
l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
```
I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:
```
[39, 6, 13, 50]
```
Then I wa... | A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax:
```
>>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
>>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t
...
>>> sorted(l, key=asum)
[[1, 2, 3], [4, [5,... | A little recursive function would do it:
```
def asum(a):
if isinstance(a, list):
return sum(asum(x) for x in a)
else:
return a
l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
l.sort(key=asum)
print l
``` | Python - sort a list of nested lists | [
"",
"python",
"list",
"sorting",
"nested-lists",
""
] |
I want to add an item to an ASP.Net combobox using Javascript. I can retrieve the ID (No Masterpage). How can I add values to the combobox from Javascript? My present code looks like this.
```
//Fill the years (counting 100 from the first)
function fillvarYear() {
var dt = $('#txtBDate').val();
... | To see the value on postback:
```
string selectedValue = Request.Params[combobox.UniqueId]
```
Remember, changing the values in a combobox with javascript will cause an Event Validation exception to be thrown, and is generally a bad idea, as you'll have to explicitly disabled event validation.
I'd recommend placing ... | Always remember, ASP.NET controls are nothing "fancy" - they always end up at some point becoming standard HTML elements.
Try checking out [this site](http://www.mredkj.com/tutorials/tutorial005.html). It has a pretty nice demo and overview. Take note however that you are **altering the data at the client side - this ... | I want to add items to an ASP.Net combobox using Javascript | [
"",
"asp.net",
"javascript",
""
] |
I have a single string that contains the command-line parameters to be passed to another executable and I need to extract the string[] containing the individual parameters in the same way that C# would if the commands had been specified on the command-line. The string[] will be used when executing another assemblies en... | In addition to the [good and pure managed solution](https://stackoverflow.com/questions/298830/split-string-containing-command-line-parameters-into-string-in-c/298990#298990) by [Earwicker](https://stackoverflow.com/users/27423/earwicker), it may be worth mentioning, for sake of completeness, that Windows also provides... | It annoys me that there's no function to split a string based on a function that examines each character. If there was, you could write it like this:
```
public static IEnumerable<string> SplitCommandLine(string commandLine)
{
bool inQuotes = false;
return commandLine.Split(c =>
... | Split string containing command-line parameters into string[] in C# | [
"",
"c#",
"command-line",
"text-parsing",
""
] |
I am attempting to use a Stream Result to return an image from a struts2 application. I seem to be having problem with configuring the action. Here is the configuration:
```
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStrea... | I found [this](http://www.nabble.com/Struts-2-File-upload-to-store-the-filedata-td14168069.html) which explained that the `InputStream` has to be created by me. It makes sense that I create an `InputStream` from the file that I want the user to download and then pass the Stream to the result. I guess that's my answer. | I believe you have the contentDisposition wrong, it should be:
```
<param name="contentDisposition">attachment; filename="${filename}"</param>
```
(*Chris*) | Using Stream Result with Struts2 | [
"",
"java",
"struts2",
"resulttype",
""
] |
Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:
```
$("<div></div>");
```
However, I'm getting the feeling that this isn't the best or the most efficient method of do... | I use `$(document.createElement('div'));` [Benchmarking shows](http://jsperf.com/jquery-vs-createelement) this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself.
You should really run benchmarks with different Javascript engines and wei... | personally i'd suggest (for readability):
```
$('<div>');
```
some numbers on the suggestions so far (safari 3.2.1 / mac os x):
```
var it = 50000;
var start = new Date().getTime();
for (i = 0; i < it; ++i) {
// test creation of an element
// see below statements
}
var end = new Date().getTime();
alert( end -... | What is the most efficient way to create HTML elements using jQuery? | [
"",
"javascript",
"jquery",
"html",
"dom",
""
] |
Im thinking of updating my practices, and looking for a little help and advice!
I do a lot of work on sites that run joomla, oscommerce, drupal etc and so I have created a lot of custom components/plugins and hacks etc. Currently each site has its own folder on my xampp setup. What I would like to do is have a default... | Yes, SVN would be a great tool for this purpose. Store your code (eg: a custom Joomla component) in source control. Wherever you want to use that component, just do a `checkout` or `export` of that particular folder into your live site. Here's one way you could structure your repository:
```
unfuddle.com/myRepo/trunk/... | For automating things, you could use SVN hooks for this. There is a post-commit hook, so every time you do a commit, your hook script could tell the other machines to do an SVN update to get the latest code.
For more info, see [Version Control with Subversion - Implementing Repository Hooks](http://svnbook.red-bean.co... | IDE, SVN and pushing to sites! | [
"",
"php",
"svn",
"ide",
"aptana",
"unfuddle",
""
] |
How can I bring my WPF application to the front of the desktop? So far I've tried:
```
SwitchToThisWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle, true);
SetWindowPos(new WindowInteropHelper(Application.Current.MainWindow).Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
SetForegroun... | Well I figured out a work around. I'm making the call from a keyboard hook used to implement a hotkey. The call works as expected if I put it into a BackgroundWorker with a pause. It's a kludge, but I have no idea why it wasn't working originally.
```
void hotkey_execute()
{
IntPtr handle = new WindowInteropHelper... | ```
myWindow.Activate();
```
*Attempts to bring the window to the foreground and activates it.*
That should do the trick, unless I misunderstood and you want Always on Top behavior. In that case you want:
```
myWindow.TopMost = true;
``` | Bring a window to the front in WPF | [
"",
"c#",
".net",
"wpf",
"winapi",
"pinvoke",
""
] |
I want to learn how to create **truly** robust applications in .net - ones that are fault tolerant and are capable of withstanding unexpected situations. Where can I find literature/guidance on this subject? So far, I am not having much luck. | I'm aware of at least a couple resources. First, there's a very useful article on MSDN titled [Keep Your Code Running with the Reliability Features of the .NET Framework](http://msdn.microsoft.com/en-us/magazine/cc163716.aspx).
Chris Brumme also had a [post on hosting](http://blogs.msdn.com/cbrumme/archive/2004/02/21/... | If you are looking from a software implementation perspective, then it may be worth looking into [Design by Contract (DbC)](http://en.wikipedia.org/wiki/Design_by_contract)
According to [this source](http://archive.eiffel.com/doc/manuals/technology/contract/), the benefits of Design by Contract include the following:
... | Redundancy, reliability and fault tolerance in C# - where to look for examples? | [
"",
"c#",
"reliability",
"redundancy",
""
] |
Does anyone know what is wrong with this query?
```
SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate, c.DTN as
DocTrackNumber
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.It... | You will need to modify the query as such:
```
SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate, c.DTN as
DocTrackNumber, a.DateStored
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNu... | Nevermind, executing in SQL Plus gave me a more informative answer. The DateStored needs to be in the select statement so this works:
```
SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate,
c.DTN as DocTrackNumber,
a.DateStored
FROM ItemData a,
ItemDataPage b, ... | Oracle PL/SQL Query Order By issue with Distinct | [
"",
"sql",
"oracle",
""
] |
I am using Context.RewritePath() in ASP.NET 3.5 application running on IIS7.
I am doing it in application BeginRequest event and everything works file.
Requests for /sports are correctly rewritten to default.aspx?id=1, and so on.
The problem is that in my IIS log I see GET requests for /Default.aspx?id=1 and not for... | After some research, I've finally found a solution to the problem.
I have replaced the calls to Context.RewritePath() method with the new (introduced in ASP.NET 3.5) **Context.Server.TransferRequest()** method.
It seems obvious now, but not event Senior Dev Engineer on IIS Core team thought of that.
I've tested it f... | You could set the path back to the original value after the request has been processed but before the IIS logging module writes the log entry.
For example, this module rewrites the path on `BeginRequest` and then sets it back to the original value on `EndRequest`. When this module is used the original path appears in ... | IIS7, RewritePath and IIS log files | [
"",
"c#",
"asp.net",
"iis-7",
"url-rewriting",
"logging",
""
] |
All the member variables and member functions in my class ClassA are static.
If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user fro... | Like others said, a namespace is what you should use. If you want to stay with your class, create a class that has a private constructor, and derive from it, to make your intention obvious:
```
class NonConstructible {
NonConstructible();
};
class SuperUtils: NonConstructible {
static void foo();
// ...
... | Instead of using a class with all static methods, you may be better off making the methods free-standing functions in a separate namespace. The call syntax would be the same:
`namespace::function()` instead of `classname::function()`
and you don't need to deal with someone trying to instantiate your class. | Prevent creation of class whose member functions are all static | [
"",
"c++",
"static",
"constructor",
"namespaces",
""
] |
I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.
The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.
The two ways are:
```
var functio... | The difference is that `functionOne` is a function expression and so only defined when that line is reached, whereas `functionTwo` is a function declaration and is defined as soon as its surrounding function or script is executed (due to [hoisting](http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.... | First I want to correct Greg: `function abc(){}` is scoped too — the name `abc` is defined in the scope where this definition is encountered. Example:
```
function xyz(){
function abc(){};
// abc is defined here...
}
// ...but not here
```
Secondly, it is possible to combine both styles:
```
var xyz = function a... | var functionName = function() {} vs function functionName() {} | [
"",
"javascript",
"function",
"methods",
"syntax",
""
] |
I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python `SimpleHTTPServer.SimpleHTTPRequestHandler`?
A simple example would be a textfield and a bu... | O.K., I think I can now answer my own question. Here is an example implementation for calculating the square of a number on the server. Please let me know if there are any improvements or misconceptions.
the python server file:
```
import threading
import webbrowser
import BaseHTTPServer
import SimpleHTTPServer
FILE... | Use the [WSGI reference implementation](https://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server). In the long run, you'll be happier.
```
from wsgiref.simple_server import make_server, demo_app
httpd = make_server('', 8000, demo_app)
print "Serving HTTP on port 8000..."
# Respond to requests unti... | How to implement a minimal server for AJAX in Python? | [
"",
"python",
"ajax",
"user-interface",
""
] |
Can any one explain why the output of this code is only 'hello' and what this code means?
```
( 0, characterArray, 0, characterArray.Length );
```
The output is showing:
```
The character array is: hello
```
The code follows:
```
string string1 = "hello there";
char[] characterArray = new char[ 5 ];
string1.CopyT... | It's because your array is only set for 5 characters. Expand it to 11 and it will work.
Here is what the Copyto is:
```
public void CopyTo(
int sourceIndex,
char[] destination,
int destinationIndex,
int count
)
```
```
Parameters
sourceIndex
Type: System..::.Int32
A character position in this instanc... | It's only showing 'hello' because your character array is only 5 chars long. As for the parameters to CopyTo, read <http://msdn.microsoft.com/en-us/library/system.string.copyto.aspx> | What is String.CopyTo? | [
"",
"c#",
""
] |
I have a need to evaluate user-defined logical expressions of arbitrary complexity on some PHP pages. Assuming that form fields are the primary variables, it would need to:
* substitute"varibles" for form
fields values;
* handle comparison operators,
minimally ==, <, <=, >= and > by
symbol, name (eg eq, lt, le, ... | Check [create\_function](http://www.php.net/create_function), it creates an anonymous function from the string parameters passed, I'm not sure about its performance, but it's very flexible... | Much time has gone by since this question was asked, and I happened to be looking for an expression parser for php. I chose to use the [ExpressionLanguage](https://symfony.com/doc/current/components/expression_language.html) component from Symfony 2.4. It can be installed with no dependencies from composer via [packagi... | Dynamic logical expression parsing/evaluation in PHP? | [
"",
"php",
"parsing",
""
] |
> **Possible Duplicate:**
> [Can’t operator == be applied to generic types in C#?](https://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c)
I've got the following generic class and the compiler complains that "`Operator '!=' cannot be applied to operands of type 'TValue' and 'TValue... | Did you try something like this?
```
public class Example<TValue>
{
private TValue _value;
public TValue Value
{
get { return _value; }
set
{
if (!object.Equals(_value, value))
{
_value = value;
OnPropertyChanged("Value");
... | Three options:
* Constrain TValue to implement `IEquatable<TValue>` and then call `x.Equals(y)`
* Take another parameter of type `IEqualityComparer<TValue>` and use that
* Use `EqualityComparer<TValue>.Default` to perform the comparisons
You could always mix and match options 2 and 3, of course - default to the defau... | How to compare two elements of the same but unconstrained generic type for equality? | [
"",
"c#",
"generics",
"class",
"struct",
"equals",
""
] |
I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.
For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments... | Take a look at django's built-in [contenttypes framework](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#ref-contrib-contenttypes):
`django.contrib.contenttypes`
It allows you develop your applications as stand-alone units. This is what the django developers used to allow django's built-in [comment fr... | "Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact?"
Yep. Works for me.
We have about 10 applications that borrow back and forth among themselves.
This leads to a kind of dependency in our unit test script.
It looks like this.
* "ownership". We have... | Beginner: Trying to understand how apps interact in Django | [
"",
"python",
"django",
"django-models",
"django-apps",
""
] |
I have a custom XML schema defined for page display that puts elements on the page by evaluating XML elements on the page. This is currently implemented using the preg regex functions, primarily the excellent preg\_replace\_callback function, eg:
```
...
$s = preg_replace_callback("!<field>(.*?)</field>!", replace_fie... | PHP's [`XSLTProcessor`](https://www.php.net/manual/en/class.xsltprocessor.php) class ([ext/xsl](https://www.php.net/manual/en/book.xsl.php) - PHP 5 includes the XSL extension by default and can be enabled by adding the argument `--with-xsl[=DIR]` to your configure line) is quite sophisticated and allows among other thi... | You can use XSL to do this - just match the inner patterns first.
Here is a good starting point for learning what you can do with XSL:
<http://www.w3schools.com/xsl/>
You can perform the xsl transformation server side or in the client (using js, activex or other).
If you still hate this idea of xsl you could look a... | XML parsing and transformation in PHP? | [
"",
"php",
"xml",
"regex",
"parsing",
""
] |
I have a site that connects using cURL (latest version) to a secure gateway for payment.
The problem is cURL always returns 0 length content. I get headers only. And only when I set cURL to return headers. I have the following flags in place.
```
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURL... | You should also try checking the error messages in curl\_error(). You might need to do this once after each curl\_\* function.
<http://www.php.net/curl_error> | I had the same problem today.
Curl comes with an outdated file to authenticate HTTPS certificates from.
get the new one from:
<http://curl.haxx.se/ca/cacert.pem>
save it into some dir on your site
and add
```
curl_setopt ($curl_ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");
```
To every request :-)
IGNORE... | Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do? | [
"",
"php",
"curl",
"https",
""
] |
In C# is there a technique using reflection to determine if a method has been added to a class as an extension method?
Given an extension method such as the one shown below is it possible to determine that Reverse() has been added to the string class?
```
public static class StringExtensions
{
public static strin... | You have to look in all the assemblies where the extension method may be defined.
Look for classes decorated with [`ExtensionAttribute`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx), and then methods within that class which are *also* decorated with `ExtensionAttribu... | Based on John Skeet's answer I've created my own extension to the System.Type-type.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System
{
public static class TypeExtension
{
/// <summary>
/// Th... | Reflection to Identify Extension Methods | [
"",
"c#",
"reflection",
"extension-methods",
""
] |
I need to edit (using javascript) an SVG document embedded in an html page.
When the SVG is loaded, I can access the dom of the SVG and its elements. But I am not able to know if the SVG dom is ready or not, so I cant' perform default actions on the SVG when the html page is loaded.
To access the SVG dom, I use this ... | You could try polling every so often.
```
function checkReady() {
var svg = document.getElementById("chart").getSVGDocument();
if (svg == null) {
setTimeout("checkReady()", 300);
} else {
...
}
}
``` | On your embedding element (e.g 'embed', 'object', 'iframe') in the main document add an `onload` attribute which calls your function, or add the event listener in script, e.g `embeddingElm.addEventListener('load', callbackFunction, false)`. Another option might be to listen for `DOMContentLoaded`, depends on what you w... | How to check if an embedded SVG document is loaded in an html page? | [
"",
"javascript",
"jquery",
"dom",
"svg",
""
] |
What's the easiest way to use a linked list in Python? In Scheme, a linked list is defined simply by `'(1 2 3 4 5)`.
Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to refere... | Here is some list functions based on [Martin v. Löwis's representation](https://stackoverflow.com/questions/280243/python-linked-list#280284):
```
cons = lambda el, lst: (el, lst)
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)
car = lambda lst: lst[0] if lst else lst
cdr = lambda ... | For some needs, a [deque](https://docs.python.org/library/collections.html#collections.deque) may also be useful. You can add and remove items on both ends of a deque at O(1) cost.
```
from collections import deque
d = deque([1,2,3,4])
print d
for x in d:
print x
print d.pop(), d
``` | How can I use a Linked List in Python? | [
"",
"python",
"linked-list",
""
] |
I have a command-line process I would like to automate and capture in C#.
At the command line, I type:
```
nslookup
```
This launches a shell which gives me a > prompt. At the prompt, I then type:
```
ls -a mydomain.local
```
This returns a list of local CNAMEs from my primary DNS server and the physical machines ... | ```
ProcessStartInfo si = new ProcessStartInfo("nslookup");
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
Process nslookup = new Process(si);
nslookup.Start();
nslookup.StandardInput.WriteLine("ls -a mydomain.local");
nslookup.StandardInput.Flush();
// use nslookup.StandardOutput stream to read the... | Not what you asked, but I once wrote an app that did what you're doing. I eventually moved to using a .NET library to do the DNS lookups, which turned out to be a lot faster.
I'm pretty sure I used [this library](http://www.codeproject.com/KB/IP/DNS_NET_Resolver.aspx) from the CodeProject site. | Capturing nslookup shell output with C# | [
"",
"c#",
"shell",
".net-2.0",
"nslookup",
""
] |
I plan on using MySQL and it's built-in encryption functionality to encrypt / decrypt certain columns in certain tables. The concern I have is that I need to store the key somewhere. I could certainly store the key in a file and control the permissions of that file and the permissions of the application that accesses i... | I'm not sure if using MySQL build in encryption would be the best solution to your problem.
PHP's [M\_CRYPT](http://www.php.net/manual/en/intro.mcrypt.php) package is thought to be quite good and it gives you the flexibility to choose the algorithm that is best suited for your needs.
Storing your key on some other se... | I'd probably store it in a file that is in a non-web-accessible directory and locked down with file system permissions as much as possible.
Your web-facing script should not open any file system files using variables, especially user-provided ones. Don't even give them the option of slipping something passed your inpu... | What's the best method to use / store encryption keys in MySQL | [
"",
"php",
"mysql",
"security",
"encryption",
"key",
""
] |
I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript.
HTML:
```
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
```
CSS:
```
.menuItem{
disp... | Your code looks fine to me.
Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:
```
$(function() {
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
``` | I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.
You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "... | jQuery hover and class selector | [
"",
"javascript",
"jquery",
"html",
"css",
""
] |
Does anyone know where I can find an example of how to determine if the Maximize and/or Minimize buttons on a window are available and/or disabled?
The window will not be in the same process as my application. I have the hWnd and I have tried using GetMenuItemInfo, but I can't find any good samples for how to do this.... | ```
bool has_maximize_btn = (GetWindowLong(hWnd, GWL_STYLE) & WS_MAXIMIZEBOX) != 0;
bool has_minimize_btn = (GetWindowLong(hWnd, GWL_STYLE) & WS_MINIMIZEBOX) != 0;
``` | The Win32 API provides the [**GetTitleBarInfo** function](http://msdn.microsoft.com/en-us/library/ms633513(VS.85).aspx) which returns a [**TITLEBARINFO** Structure](http://msdn.microsoft.com/en-us/library/ms632608(VS.85).aspx):
```
typedef struct {
DWORD cbSize;
RECT rcTitleBar;
DWORD rgstate[CCHILDREN_TIT... | Determining if the Maximize button is available | [
"",
"c#",
"winapi",
""
] |
is there a managed code (without adding COM component or wrapped called to C++ routines) way to add integrated security to a C# Managed code assembly?
i.e. I want to write a client-server system where the server uses Remoting instead of IIS, but I want the client to automatically pass it's credentials to the server ju... | No - there is no pure managed interface to [SSPI](http://msdn.microsoft.com/en-us/library/aa380493(VS.85).aspx). But, there is an MSDN sample that [wraps SSPI for you](http://msdn.microsoft.com/en-us/library/ms973911.aspx), and then [uses the wrapper for remoting](http://msdn.microsoft.com/en-us/library/ms973909.aspx). | .NET 2 has NegotiateStream which is used by TCP remoting to provide SSPI. | Integrated Security | [
"",
"c#",
"remoting",
"windows-authentication",
""
] |
How can I receive and send email in python? A 'mail server' of sorts.
I am looking into making an app that listens to see if it receives an email addressed to foo@bar.domain.com, and sends an email to the sender.
Now, am I able to do this all in python, would it be best to use 3rd party libraries? | Here is a very simple example:
```
import smtplib
server = 'mail.server.com'
user = ''
password = ''
recipients = ['user@mail.com', 'other@mail.com']
sender = 'you@mail.com'
message = 'Hello World'
session = smtplib.SMTP(server)
# if your SMTP server doesn't need authentications,
# you don't need the following line... | Found a helpful example for reading emails by connecting using IMAP:
[Python — imaplib IMAP example with Gmail](http://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/)
```
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername@gmail.com', 'mypassword')
mail.list()
# Out... | Receive and send emails in python | [
"",
"python",
"email",
""
] |
I'm a little new to the Java 5 annotations and I'm curious if either of these are possible:
This annotation would generate a simple getter and setter for you.
```
@attribute
private String var = "";
```
The `@NotNull` annotation indicates that a variable connot be null so you don't have to write that boilerplate cod... | Annotation processing occurs on the abstract syntax tree. This is a structure that the parser creates and the compiler manipulates.
The current specification (link to come) says that annotation processors cannot alter the abstract syntax tree. One of the consequences of this is that it is not suitable to do code gener... | Getters/Setters: Yes, it is possible. The [Project Lombok](http://projectlombok.org/features/index.html) (<http://projectlombok.org/index.html>) defines annotations for generating getters/setters and more.
So for example
```
@lombok.Data;
public class Person {
private final String name;
private int age;
}
```
... | Is there a way to use annotations in Java to replace accessors? | [
"",
"java",
"annotations",
"metaprogramming",
""
] |
I'm using hibernate 3 and want to stop it from dumping all the startup messages to the console. I tried commenting out the stdout lines in log4j.properties but no luck. I've pasted my log file below. Also I'm using eclipse with the standard project structure and have a copy of log4j.properties in both the root of the p... | Try to set more reasonable logging level. Setting logging level to `info` means that only log event at `info` or higher level (`warn`, `error` and `fatal`) are logged, that is `debug` logging events are ignored.
```
log4j.logger.org.hibernate=info
```
or in [XML version](http://wiki.apache.org/logging-log4j/Log4jXmlF... | Important notice: the property (part of hibernate configuration, NOT part of logging framework config!)
```
hibernate.show_sql
```
controls the logging *directly* to STDOUT bypassing any logging framework (which you can recognize by the missing output formatting of the messages). If you use a logging framework like l... | Turning off hibernate logging console output | [
"",
"java",
"hibernate",
"logging",
""
] |
The code I have pasted below is meant to display images on the middle 2 links without text and go back to text on the reset and fourth link. I have set display:none for the span tag only, but it does nothing. Is there anyway to do what I am after simply, without using a framework?
edit: example
```
<html>
<head>
... | The `rel` attribute is supposed to describe the relationship of the link to the current document. It should have one of the values described [here](http://www.w3.org/TR/html401/types.html#type-links). A DIV is a block-level grouping element, whereas a SPAN is an inline grouping element. SPANs allow you to group text an... | The div tag encloses a block of content. The span tag is similar, but encloses inline content. Difference? You can use span to style a phrase inside a paragraph, but div to wrap that paragraph and separate it from others. See [this](http://www.w3schools.com/tags/tag_DIV.asp) for divs, and [this](http://www.w3schools.co... | css page problem | [
"",
"javascript",
"html",
"css",
""
] |
I need to perform a HTTP GET from PHP.
More specifically, from within /index.php I need to get the content of /trac/ and /svn/, find the "ul" element and then render then inline on the index.php.
/trac and /svn are relative URLs and not filesystem folders.
<http://myserver/trac> and <http://myserver/svn> | The simplest way is [`file_get_contents()`](http://www.php.net/file_get_contents).
```
$str = file_get_contents('http://myserver/svn/');
// Or, if you don't want to hardcode the server
$str = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . '/svn/');
if ($str)
{
// Find the ul
}
``` | I suggest you have a look at...
* the [HTTP\_Request2](http://pear.php.net/package/HTTP_Request2) PEAR Package,
* the [CURL Library](http://de3.php.net/manual/en/book.curl.php) in PHP (if installed) or
* plain [Filesystem Functions](http://de3.php.net/manual/en/ref.filesystem.php) in PHP (if you have [allow\_url\_fope... | PHP HttpRequest | [
"",
"php",
""
] |
Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.
```
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
`... | Just use [`array_merge`](https://www.php.net/manual/en/function.array-merge.php) or [`array_replace`](https://www.php.net/manual/en/function.array-replace.php). `array_merge` works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:
```
$custom... | There you go:
```
function sortArrayByArray(array $array, array $orderArray) {
$ordered = array();
foreach ($orderArray as $key) {
if (array_key_exists($key, $array)) {
$ordered[$key] = $array[$key];
unset($array[$key]);
}
}
return $ordered + $array;
}
``` | Custom key-sort a flat associative based on another array | [
"",
"php",
"arrays",
"sorting",
"key",
"associative-array",
""
] |
Where I work, people mostly think that objects are best initialised using C++-style construction (with parentheses), whereas primitive types should be initialised with the = operator:
```
std::string strFoo( "Foo" );
int nBar = 5;
```
Nobody seems to be able to explain why they prefer things this way, though. I can s... | Unless you've proven that it matters with respect to performance, I wouldn't worry about an extra copy using the assignment operator in your example (`std::string foo = "Foo";`). I'd be pretty surprised if that copy even exists once you look at the optimized code, I believe that will actually call the appropriate param... | Initializing variables with the = operator or with a constructor call are semantically the same, it's just a question of style. I prefer the = operator, since it reads more naturally.
Using the = operator *usually* does not generate an extra copy - it just calls the normal constructor. Note, however, that with non-pri... | Why use = to initialise a primitive type in C++? | [
"",
"c++",
"coding-style",
"c++03",
""
] |
I've used [UPX](http://upx.sourceforge.net/) before to reduce the size of my Windows executables, but I must admit that I am naive to any negative side effects this could have. What's the downside to all of this packing/unpacking?
Are there scenarios in which anyone would recommend NOT UPX-ing an executable (e.g. when... | > ... there are downsides to
> using EXE compressors. Most notably:
>
> * Upon startup of a compressed EXE/DLL, all of the code is
> decompressed from the disk image into
> memory in one pass, which can cause
> disk thrashing if the system is low on
> memory and is forced to access the
> swap file. In contras... | I'm surprised this hasn't been mentioned yet but using UPX-packed executables also increases the risk of producing false-positives from heuristic anti-virus software because statistically a lot of malware also uses UPX. | Are there any downsides to using UPX to compress a Windows executable? | [
"",
"c++",
"delphi",
"winapi",
"compression",
"upx",
""
] |
I'm wondering what good ways there would be make assertions about synchronization or something so that I could detect synchronization violations (while testing).
That would be used for example for the case that I'd have a class that is not thread-safe and that isn't going to be thread-safe. With some way I would have ... | You are looking for the holy grail, I think. AFAIK it doesn't exist, and Java is not a language that allows such an approach to be easily created.
"Java Concurrency in Practice" has a section on testing for threading problems. It draws special attention to how hard it is to do. | When an issue arises over threads in Java it is usually related to deadlock detection, more than just monitoring what Threads are accessing a synchronized section at the same time. [JMX](http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/) extension, added to JRE since 1.5, can help you detect those ... | How to detect synchronization violations with Java | [
"",
"java",
"multithreading",
"synchronization",
"error-detection",
""
] |
I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use `os.walk` but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never b... | ```
import glob, os, shutil
files = glob.iglob(os.path.join(source_dir, "*.ext"))
for file in files:
if os.path.isfile(file):
shutil.copy2(file, dest_dir)
```
Read the [documentation](http://www.python.org/doc/2.5.2/lib/module-shutil.html) of the shutil module to choose the function that fits your needs (... | If you're not recursing, you don't need walk().
Federico's answer with glob is fine, assuming you aren't going to have any directories called ‘something.ext’. Otherwise try:
```
import os, shutil
for basename in os.listdir(srcdir):
if basename.endswith('.ext'):
pathname = os.path.join(srcdir, basename)
... | How do I copy files with specific file extension to a folder in my python (version 2.5) script? | [
"",
"python",
"file",
"copy",
""
] |
Can anyone explain the difference between the types mentioned above and some sample usage to clearly explain the difference between the two?
Any help would be highly appreciated!
Note: this question is a spin-off from [this other question](https://stackoverflow.com/questions/324168/msxml2ixmldomdocument2ptr-getxml-mes... | `BSTR` is the string data type used with COM.
`_bstr_t` is a wrapper class that works like a smart pointer, so it will free the allocated memory when the variable is destroyed or goes out of scope.
`_bstr_t` also has reference counting, which increases every time you pass the `_bstr_t` variable by value (avoiding unne... | **BSTR** is a raw pointer, while **`_bstr_t`** is a class encapsulating that pointer.
It's the same difference as **char\*** vs. **std::string**. | What's the difference between BSTR and _bstr_t? | [
"",
"c++",
"com",
"smart-pointers",
""
] |
Are there any alternatives to JSTL? One company I worked for 3 years ago used JSTL and custom tag libraries to separate presentation from logic. Front-end developers used EL to do complex presentation logic, generate layouts in JSP pages and it worked out great. Perhaps new technologies have come out. Anything better t... | JSTL and EL are two distinct concepts.
JSTL is just one tag library. Most frameworks provide their own taglib that approximately duplicates the functionality of JSTL. I say approximately, because these often misuse or overlook key principles of JSP and the Servlet API.
The strength of JSTL is that it was designed by ... | I've used [velocity](http://velocity.apache.org/) with great success and it works great as a simple way to separate business logic from presentation logic. And it's simple enough that your average web developer can understand it. [Freemarker](http://freemarker.sourceforge.net/) is another templating alternative that a ... | What are the alternatives to JSTL? | [
"",
"java",
"model-view-controller",
"jsp",
"jstl",
""
] |
With generics, is there ever a reason to create specific derived EventArg classes
It seems like now you can simply use them on the fly with a generic implementation.
Should i go thorugh all of my examples and remove my eventArg classes (StringEventArgs, MyFooEventArgs, etc . .)
```
public class EventArgs<T> : EventA... | What you are describing are essentially [tuples](http://en.wikipedia.org/wiki/Tuple), grouped values used for a particular purpose. They are a useful construct in [functional programming](http://en.wikipedia.org/wiki/Functional_programming) and support that style very well.
The downside is that their values are not na... | Look at the [Custom Generic EventArgs](http://www.c-sharpcorner.com/UploadFile/rmcochran/customgenericeventargs05132007100456AM/customgenericeventargs.aspx) article written by [Matthew Cochran](http://www.c-sharpcorner.com/Authors/AuthorDetails.aspx?AuthorID=rmcochran), in that article he describes how to expand it eve... | Are EventArg classes needed now that we have generics | [
"",
"c#",
"generics",
"eventargs",
""
] |
I am making a Color class, and provide a standard constructor like
```
Color(int red, int green, int blue)
```
And then I want to provide an easy way to get the most common colors, like
Color.Blue, Color.Red. I see two possible options:
```
public static readonly Color Red = new Color(255, 0, 0);
public static Colo... | I'm guessing that you're probably already aware that the framework provides a `Color` struct. I'm guessing that you're creating a `Color` class just for practice.
You expressed uncertainty about the meaning of the `static` keyword, although you've used it correctly. When `static` is applied to a member of a class or s... | Your reasoning and identification of the trade-off seems sound. If you look at the System.Drawing.Color structure, you'll see it uses the second technique. The overhead of initializing a new struct is trivial, so this is probably better than having a large number of known colors pre-created.
I would expect Color to be... | C#, correct use of the static keyword when designing a basic color class | [
"",
"c#",
"static",
""
] |
In the standard PrintDialog there are four values associated with a selected printer: Status, Type, Where, and Comment.
If I know a printer's name, how can I get these values in C# 2.0? | As [dowski suggested](https://stackoverflow.com/questions/296182/how-to-get-printer-info-in-cnet#296232), you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.
```
using Sy... | This *should* work.
```
using System.Drawing.Printing;
```
...
```
PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting
```
After that, the various [properties](http://msdn.microsoft.com/en-us/library/system.drawing.printing.printersettings_membe... | How to get Printer Info in .NET? | [
"",
"c#",
".net",
"printing",
"printers",
"printdialog",
""
] |
Although I know how to build a DOM the long, arduous way using the DOM API, I'd like to do something a bit better than that. Is there a nice, tidy way to build hierarchical documents with, say, an API that works something like Hibernate's Criteria API? So that I can chain calls together like this, for example:
```
Doc... | You definitely want to use `JDom`: <http://www.jdom.org/docs/apidocs/> . It can be used as you described as many methods return a reference to `this`. Here is some code our teacher showed us for this XML document. Haven't tested it, but the teacher is great i believe in him:
```
<adressbuch aktualisiert="1.4.2008">
... | I highly recommend Elliotte Rusty Harold's [XOM](http://xom.nu/) API.
It inter-operates with the W3C API, in that you can convert between XOM and DOM. The API guarantees a well-formed structure at all times. It's performant, robust, and follows consistent design principles. | What is an efficient way to create a W3C DOM programatically in Java? | [
"",
"java",
"xml",
"dom",
""
] |
I have below a list of text, it is from a popular online game called EVE Online and this basically gets mailed to you when you kill a person in-game. I'm building a tool to parse these using PHP to extract all relevant information. I will need all pieces of information shown and i'm writting classes to nicely break it ... | If you want something flexible, use the state machine approach.
If you want something quick and dirty, use regexp.
For the first solution, you can use libraries that are specialized in parsin since it's not a trivial task. But because it's fairly simple format, you can hack a naive parser, as for example :
```
<?php... | I'd probably go with a state machine approach, reading each line in sequence and dealing with it depending on the current state.
Some lines, like "Dropped items:" change the state, causing you to interpret following lines as items. While in the "reading involved parties" state you'd be adding each line to an array of ... | Best way to parse a dynamic text list in PHP | [
"",
"php",
"regex",
"text",
"parsing",
""
] |
Using LINQ to Entities sounds like a great way to query against a database and get actual CLR objects that I can modify, data bind against and so forth. But if I perform the same query a second time do I get back references to the same CLR objects or an entirely new set?
I do not want multiple queries to generate an e... | Within the same DataContext, my understanding is that you'll always get the same objects - for queries which return full objects instead of projections.
Different DataContexts will fetch different objects, however - so there's a risk of seeing stale data there, yes. | In the same DataContext you would get the same object if it's queried (DataContext maintains internal cache for this).
Be aware that that the objects you deal are most likely mutable, so instead of one problem (data duplication) you can get another (concurrent access).
Depending on business case it may be ok to let t... | Does LINQ to Entities reuse instances of objects? | [
"",
"c#",
"linq",
"entities",
""
] |
How can I compile/run C or C++ code in a Unix console or a Mac terminal? | If it is a simple single-source program,
```
make foo
```
where the source file is *foo.c*, *foo.cpp*, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.
Running the executable just built is the same as running any ... | ```
gcc main.cpp -o main.out
./main.out
``` | How can I compile and run C/C++ code in a Unix console or Mac terminal? | [
"",
"c++",
"c",
"macos",
"console",
"terminal",
""
] |
i connecting to a access database with php and adodb. Strings with characters like ® are saved in the database as ® .
What can i do to store it correctly? | Looks like you're passing in a UTF8 string but you're not storing it as UTF8. Change it one way or the other so they match up (preferably change your database to UTF8). | @RoBOrg: Yes, but i didn't find a way to store it as utf8. The connection string is allready with charset=utf8 "DRIVER=Microsoft Access Driver (\*.mdb);DBQ=something.mdb;UID=Administrator;Charset=utf8" and i didn't find any possibility in adodb to change the storing charset for access databases.
I'm updating with comma... | adodb and access changing ® to ® | [
"",
"php",
"ms-access",
"adodb",
""
] |
I need to validate a certain property to one of my classes. When I set the property, the class should validate the input and if incorrect, set the object to an invalid state.
Question : The property value must be in a certain mask/format eg. &&&&-&&&&-&&&&. I cannot use regular expressions. Is it possible to validate ... | Regular expressions are often over-used, but this is a pretty good example of when a regex is ideal... so: why can't you use them here? | > Is it possible to validate text
> against a mask value ?
Of course it's possible, in that you could write a function to take a string and a mask and check one against another.
So I'm unclear on what you're asking - are you asking if there are functions in the standard .Net libraries to do this? Or asking for an imp... | Validate text against mask value in C# | [
"",
"c#",
"masking",
""
] |
Beyond the official documentation, are there any recommended resources for learning to build jQuery plugins. I'm particularly interested in building plugins for the UI libary.
I've been looking at the source for some of the official ones, but I've found they all look quite different from each other. Many are not well ... | ## Tutorial at "Learning jQuery"
[Learning jQuery](http://www.learningjquery.com) is a very helpful site, and has a [great tutorial on plugin authoring](http://www.learningjquery.com/2007/10/a-plugin-development-pattern).
One principle I really liked was: **create default settings that users can override**.
So maybe... | Have you tried the Manning Publications book on jQuery, [jQuery In Action](http://www.manning.com/bibeault/)? The [table of contents](http://www.manning.com/bibeault/excerpt_contents.html) indicates there is good material on writing your own plugins. | Building jQuery UI Plugins | [
"",
"javascript",
"jquery",
"jquery-plugins",
"jquery-ui-plugins",
""
] |
I'm building a with-source system which I am giving out on the 'net for providing adoptable virtual pets. The system will be owned mainly by kids. Since I want it to be usable for absolute beginner programmers, there are several complexity constraints on my system: It can't use libraries that don't commonly ship with P... | If you are expecting a relatively low sophistication level, then you can do a very simple "xor" encryption and "store" the key as part of the URL. Then you can just use php's rand() or /dev/random or whatever to generate keys.
Low-sophistication users won't readily figure out that all they need to do is xor the lower ... | You are looking for "one time padding" encryption. It takes a key and does modulus addition to characters to create the encrypted string.
```
function ecrypt($str){
$key = "abc123 as long as you want bla bla bla";
for($i=0; $i<strlen($str); $i++) {
$char = substr($str, $i, 1);
$keychar = substr($key, ($i... | Simple encryption in PHP | [
"",
"php",
"encryption",
""
] |
This question deals with concurrency issues, for suggestions on how to display a busy icon see this question: [Javascript - loading/busy indicator or transparent div over page on event click](https://stackoverflow.com/questions/205631/javascript-loadingbusy-indicator-or-transparent-div-over-page-on-event-click)
When a... | If you want the same busy indicator for all actions, then use a counter.
Instead of "show\_busy\_icon()", do a "increment\_busy\_count()", which calls "show\_busy\_icon()" if busy count goes from 0 to 1. Instead of "hide\_busy\_icon()", do a "decrement\_busy\_count()", which calls "hide\_busy\_icon()" if busy count go... | I think the problem is really that you are using only one indicator. It may be easier to have an indicator for each action that needs one.
So, if you have multiple searches on a page each search area would have it's own independent indicator that is shown or hidden in the appropriate javascript functions. | How do you handle busy icons in an AJAX site? | [
"",
"javascript",
"jquery",
"ajax",
"concurrency",
"callback",
""
] |
I do remember seeing someone ask something along these lines a while ago but I did a search and couldn't find anything.
I'm trying to come up with the cleanest way to clear all the controls on a form back to their defaults (e.g., clear textboxes, uncheck checkboxes).
How would you go about this? | What I have come up with so far is something like this:
```
public static class extenstions
{
private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() {
{typeof(TextBox), c => ((TextBox)c).Clear()},
{typeof(CheckBox), c => ((CheckBox)c).Che... | I know its an old question but just my 2 cents in. This is a helper class I use for form clearing.
```
using System;
using System.Windows.Forms;
namespace FormClearing
{
class Helper
{
public static void ClearFormControls(Form form)
{
foreach (Control control in form.Controls)
... | What is the best way to clear all controls on a form C#? | [
"",
"c#",
"controls",
""
] |
I'm wondering why the `assert` keyword is so underused in Java? I've almost never seen them used, but I think they're a great idea. I certainly much prefer the brevity of:
```
assert param != null : "Param cannot be null";
```
to the verbosity of:
```
if (param == null) {
throw new IllegalArgumentException("Para... | *assertions* are, in theory, for testing [invariants](http://en.wikipedia.org/wiki/Invariant_(computer_science)), assumptions that **must** be true in order for the code to complete properly.
The example shown is testing for valid input, which isn't a typical usage for an assertion because it is, generally, user suppl... | It's an abuse of assertions to use them to test user input. Throwing an `IllegalArgumentException` on invalid input is more correct, as it allows the calling method to catch the exception, display the error, and do whatever it needs to (ask for input again, quit, whatever).
If that method is a private method inside on... | Java assertions underused | [
"",
"java",
"assertion",
""
] |
On several of my usercontrols, I change the cursor by using
```
this.Cursor = Cursors.Wait;
```
when I click on something.
Now I want to do the same thing on a WPF page on a button click. When I hover over my button, the cursor changes to a hand, but when I click it, it doesn't change to the wait cursor. I wonder if... | Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using [Mouse.OverrideCursor](http://msdn.microsoft.com/en-us/library/system.windows.input.mouse.overridecursor.aspx):
```
Mouse.OverrideCursor = Cursors.Wait;
try
{
// do stuff
}
finally
{
Mou... | One way we do this in our application is using IDisposable and then with `using(){}` blocks to ensure the cursor is reset when done.
```
public class OverrideCursor : IDisposable
{
public OverrideCursor(Cursor changeToCursor)
{
Mouse.OverrideCursor = changeToCursor;
}
#region IDisposable Members
publi... | Changing the cursor in WPF sometimes works, sometimes doesn't | [
"",
"c#",
"wpf",
""
] |
Has anybody used or seen a website that uses [FlapJax](http://www.flapjax-lang.org/) to function, rather than just as a demo? I'm curious to see how they operate / how difficult they were to write.
List one example per answer. | I'm going to ignore the one app per answer request:
<http://continue2.cs.brown.edu/>
<http://resumedemo.cs.brown.edu/>
Keep in mind though that these were made by the developers of Flapjax. | I've been using it for a page internal to my employer that is largely a very fancy clock. Just using the library directly (skipping the compiler, which they plan to deprecate) has worked great. Event streams are very convenient when you've got a whole lot of different components, coming and going, that have to be synch... | Practical FlapJax | [
"",
"javascript",
""
] |
Is it possible to create an integer (or DataTime, etc) column in ListView? It is quite important, because I would like to properly sort the list according to this column.
The only way to add subItems to a ListViewItem I found are:
```
listviewitem.SubItems.Add("1");
```
I would like to avoid parsing these strings to... | You could use the Tag property. These little helper functions take care of it:
```
private void setListItem(int row, int column, int value) {
ListViewItem.ListViewSubItem item = listView1.Items[row].SubItems[column];
item.Tag = value;
item.Text = value.ToString();
}
private int getListItem(int row, int column) {... | Rather than that you just add strings to the list and receive strings by using `.Text` property.
Example:
```
int a = 0;
listView1.Items.Add(a.ToString());
```
or
```
int a = Convert.ToInt32(listView1.Items[0].SubItems[0].Text);
```
You can do this same with `DataTime` and other datatypes, just by converting them ... | Create an int column in ListView (Winforms) | [
"",
"c#",
".net",
"winforms",
""
] |
I have this function in my head:
```
<head>
window.onload = function(){
var x = new Array(0,2,3,4,5,6,7,8);
var y = new Array(20,10,40,30,60,50,70,10);
drawGraph(y,x);
}
</head>
```
Can I declare the function drawGraph() somewhere in the body? Do I need to declare it before it... | The order does matter. You'll need to have the drawGraph() function declared before it's called. | Keep in mind that many web platforms already use the window.onload method, and owing to the fact that window.onload can be called only once, you could have a script collision. You might consider using a different method for loading your script that builds the window.onload or waits for the page load to complete.
An ex... | Beginner: Javascript must be on header to run? Does the declaration order of the functions matter? | [
"",
"javascript",
""
] |
Is there an similar property like System.getProperty("java.home") that will return the JDK directory instead of the JRE directory? I've looked <https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()> and there doesn't seem to be anything for the JDK. | One route would be to set a system environment variable like "JAVA\_HOME" and use that.
It may not be the best solution, but it would work, and this is what other apps which require JDK rather than JRE (like CruiseControl) require you to do when you set them up. | There's not a property similar to `java.home` for the JDK. There are some rules of thumb that help detect whether the JRE you're running in is part of a JDK. For example, look for "${java.home}/../lib/tools.jar". In other words, in some cases, you might be able to suggest a default, but in general, the user should tell... | How can I get the location of the JDK directory in Java? | [
"",
"properties",
"java",
""
] |
This is for .NET. IgnoreCase is set and MultiLine is NOT set.
Usually I'm decent at regex, maybe I'm running low on caffeine...
Users are allowed to enter HTML-encoded entities (<lt;, <amp;, etc.), and to use the following HTML tags:
```
u, i, b, h3, h4, br, a, img
```
Self-closing <br/> and <img/> are allowed, wit... | Here's a function I wrote for this task:
```
static string SanitizeHtml(string html)
{
string acceptable = "script|link|title";
string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:(["",']?).*?\1?)?)*\s*/?>";
return Regex.Replace(html, stringPattern, "sausage");
}... | This is a good working example on html tag filtering:
[Sanitize HTML](http://web.archive.org/web/20100901160940/http://refactormycode.com/codes/333-sanitize-html) | How do I filter all HTML tags except a certain whitelist? | [
"",
"c#",
"html",
"vb.net",
"regex",
""
] |
I'm trying to read data from a.csv file to ouput it on a webpage as text.
It's the first time I'm doing this and I've run into a nasty little problem.
My .csv file(which gets openened by Excel by default), has multiple rows and I read the entire thing as one long string.
like this:
```
$contents = file_get_contents... | You are better off using [fgetcsv()](http://www.php.net/fgetcsv) which is aware of CSV file structure and has designated options for handling CSV files. Alternatively, you can use [str\_getcsv()](http://www.php.net/manual/en/function.str-getcsv.php) on the contents of the file instead. | The [file()](http://it.php.net/file) function reads a file in an array, every line is an entry of the array.
So you can do something like:
```
$rows = array();
$name = array();
$street = array();
$country = array();
$rows = file("file.csv");
foreach($rows as $r) {
$data = explode(";", $r);
$name[] = $data[0]... | problem with PHP reading CSV files | [
"",
"php",
"file-io",
"csv",
""
] |
I would like to be able to detect what country a visitor is from on my website, using PHP.
Please note that I'm not trying to use this as a security measure or for anything important, just changing the spelling of some words *(Americans seems to believe that the word "enrolment" has 2 Ls.... crazy yanks)*, and perhaps... | Not guaranteed, but most browsers submit an Accept-Language HTTP header that specifies en-us if they're from the US. Some older browsers only said they are en, though. And not all machines are set up correctly to indicate which locale they prefer. But it's a good first guess.
English-UK based-users usually set their s... | PHP provides a function since 5.3.0 to parse the `$_SERVER['HTTP_ACCEPT_LANGUAGE']` variable into a locale.
```
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale; // returns "en_US"
```
Documentation: <https://www.php.net/manual/en/locale.acceptfromhttp.php> | Simplest way to detect client locale in PHP | [
"",
"php",
"locale",
""
] |
**In brief:**
Is it ever excusable to have assembly names and class names stored in the database? Does it break the layers of an application for the data layer to have explicit knowledge of the internals of the business layer?
**Full explanation:**
I have a boot strapper that runs "jobs" (classes that inherit from a... | I think it's perfectly acceptable to store configuration info including assembly/class names in the database.
I wouldn't consider data stored in the database to be part of the data layer. | To sidestep this a little bit, with an example which justifies your implementation:
When you use an IoC container like Windsor or Unity, you store your assembly/class names in your config file. Again, this is not compiler checked, as you can change this without having to recompile your code. It's similar to storing yo... | How bad is it to store class and assembly names in the database? | [
"",
"c#",
".net",
"database",
""
] |
I'm working on some Flex spike in my company. We are basically evaluating different scenarios etc. What solution would you recommend for embedding Flex components into Java app? Flex <-> Java communication is not (yet...) an issue, just embedding swf into JFrame. | I've done it with EasyJCom. It's pretty straight forward as long as you're using one of the standard Java windowing libraries (Swing, awt). You can see an example (From the EZJCom site) here: <http://www.ezjcom.com/FlashTest.java.txt>
The people responsible for EasyJCom are also very responsive, and even though we end... | Haven't tested this, but it looks like JFlashPlayer will do the job. <http://www.jpackages.com/jflashplayer/> | Embedding Flash / Flex component into Java app | [
"",
"java",
"apache-flex",
"flash",
""
] |
How can I get a PHP function go to a specific website when it is done running?
For example:
```
<?php
//SOMETHING DONE
GOTO(http://example.com/thankyou.php);
?>
```
I would really like the following...
```
<?php
//SOMETHING DONE
GOTO($url);
?>
```
I want to do something like this:
```
<?php
//SOMETHING ... | ```
<?
ob_start(); // ensures anything dumped out will be caught
// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever
// clear out the output buffer
while (ob_get_status())
{
ob_end_clean();
}
// no redirect
header( "Location: $url" );
?>
``` | You could always just use the tag to refresh the page - or maybe just drop the necessary javascript into the page at the end that would cause the page to redirect. You could even throw that in an onload function, so once its finished, the page is redirected
```
<?php
echo $htmlHeader;
while($stuff){
echo $stu... | Redirect to specified URL on PHP script completion? | [
"",
"php",
"url",
""
] |
I am not sure what `optparse`'s `metavar` parameter is used for. I see it is used all around, but I can't see its use.
Can someone make it clear to me? Thanks. | As @Guillaume says, it's used for generating help. If you want to have an option that takes an argument, such as a filename, you can add the `metavar` parameter to the `add_option` call so your preferred argument name/descriptor is output in the help message. From [the current module documentation](http://docs.python.o... | metavar seems to be used for generating help : <http://www.python.org/doc/2.5.2/lib/optparse-generating-help.html> | Python optparse metavar | [
"",
"python",
"optparse",
""
] |
The database type is PostGres 8.3.
If I wrote:
```
SELECT field1, field2, field3, count(*)
FROM table1
GROUP BY field1, field2, field3 having count(*) > 1;
```
I have some rows that have a count over 1. How can I take out the duplicate (I do still want 1 row for each of them instead of +1 row... I do not want to de... | This is one of many reasons that all tables should have a primary key (not necessarily an ID number or IDENTITY, but a combination of one or more columns that uniquely identifies a row and which has its uniqueness enforced in the database).
Your best bet is something like this:
```
SELECT field1, field2, field3, coun... | One possible answer is:
```
CREATE <temporary table> (<correct structure for table being cleaned>);
BEGIN WORK; -- if needed
INSERT INTO <temporary table> SELECT DISTINCT * FROM <source table>;
DELETE FROM <source table>
INSERT INTO <source table> SELECT * FROM <temporary table>;
COMMIT WORK; -- needed
DROP <tempor... | Remove duplicate from a table | [
"",
"sql",
"postgresql",
""
] |
consider this code block
```
public void ManageInstalledComponentsUpdate()
{
IUpdateView view = new UpdaterForm();
BackgroundWorker worker = new BackgroundWorker();
Update update = new Update();
worker.WorkerReportsProgress = true;
worker.WorkerSuppor... | Threads count as root objects; I don't know exactly how BackgroundWorker operates, but it seems likely that the primary thread method is going to access state on the worker instance; as such, the worker thread itself will keep the BackgroundWorker instance alive until (at least) the thread has exited.
Of course; colle... | Event handlers are references, so until you have event handler attached to the worker, it would not be considered "unreachable".
In your ComplitionCallback take care to unhook the event handlers. | When will my BackgroundWorker instance be garbage collected | [
"",
"c#",
".net",
"events",
"garbage-collection",
"backgroundworker",
""
] |
What are the benefits of having a member variable declared as read only? Is it just protecting against someone changing its value during the lifecycle of the class or does using this keyword result in any speed or efficiency improvements? | The `readonly` keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the `const` modifier, which must have its value set at compile time. Using `readonly` you can set the value of the field either in the declaration, or in t... | I don't believe there are any performance gains from using a readonly field. It's simply a check to ensure that once the object is fully constructed, that field cannot be pointed to a new value.
However "readonly" is very different from other types of read-only semantics because it's enforced at runtime by the CLR. Th... | What are the benefits to marking a field as `readonly` in C#? | [
"",
"c#",
"readonly",
"processing-efficiency",
"memory-efficient",
""
] |
i want something like this
1. the user enter a website link
2. i need check the link if the link
doesn't start with 'http://' I want
to append 'http://' to the link .
how can I do that in PHP ? | ```
if (stripos($url, 'http://') !== 0) {
$url = 'http://' . $url;
}
``` | I'll recommend a slight improvement over tom's
> ```
> if (0 !== stripos($url, 'http://') && 0 !== stripos($url, 'https://')) {
> $url = 'http://' . $url;
> }
> ```
However, this will mess up links that use other protocols (ftp:// svn:// gopher:// etc) | how can i check the start of the string in php? | [
"",
"php",
"string",
"hyperlink",
""
] |
Consider the following code snippet
```
private void ProcessFile(string fullPath) {
XmlTextReader rdr = new XmlTextReader("file:\\\\" + fullPath);
while (rdr.Read()) {
//Do something
}
return;
}
```
Now, this functions fine when passed a path like:
"C:\Work Files\Technical Information\Dummy.x... | Try omitting the `file:///` protocol prefix. It works for me without one. I believe .NET will truncate any part after the `#` if it believes this to be a URL. This is only a guess based on the error message but it seems logical considering that the part after the `#` character isn't processed by the server but rather b... | Adding to Konrad's answer, if you are using the file:// protocol, you need to use %23 for # then it works fine | Hash character in path throws DirectoryNotFoundException | [
"",
"c#",
".net",
"xmltextreader",
""
] |
It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;
"loop again? y/n" | ```
while True:
func()
answer = raw_input( "Loop again? " )
if answer != 'y':
break
``` | ```
keepLooping = True
while keepLooping:
# do stuff here
# Prompt the user to continue
q = raw_input("Keep looping? [yn]: ")
if not q.startswith("y"):
keepLooping = False
``` | python - check at the end of the loop if need to run again | [
"",
"python",
"loops",
""
] |
Java and C# support the notion of classes that can't be used as base classes with the `final` and `sealed` keywords. In C++ however there is no good way to prevent a class from being derived from which leaves the class's author with a dilemma, should every class have a virtual destructor or not?
---
**Edit:** Since C... | The question is really, do you want to *enforce* rules about how your classes should be used? Why?
If a class doesn't have a virtual destructor, anyone using the class knows that it is not intended to be derived from, and what limitations apply if you try it anyway. Isn't that good enough?
Or do you need the compiler ... | Every abstract class should either have a,
* protected destructor, or,
* virtual destructor.
If you've got a public non-virtual destructor, that's no good, since it allows users to delete through that pointer a derived object. Since as we all know, that's undefined behavior.
For an abstract class, you already need a... | Should every class have a virtual destructor? | [
"",
"c++",
"virtual-destructor",
""
] |
I have an ASP.NET page that uses a repeater nested within another repeater to generate a listing of data. It's to the effect of the following:
```
<asp:Repeater>
<ItemTemplate>
<span><%#Eval("Data1") %></span>
<!-- and many more -->
<asp:Repeater DataSource='<%#Eval("Data2")%>'>
... | This won't **hide** the repeater completely, but you can subclass the Repeater control so that it includes a GridView-like empty data template:
```
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public class EmptyCapableRepeater : Repeater
{
public ITemplate EmptyDataTemplate { get; set; }
... | Try something like:
```
<asp:Repeater runat="server" DataSource='<%#Eval("Data2")%>'
Visible='<%# ((IEnumerable)Eval("Data2")).GetEnumerator().MoveNext() %>'>
```
for the nested repeater | How can I hide a repeater in ASP.NET C# if the DataSource contains no items? | [
"",
"c#",
"asp.net",
"repeater",
""
] |
When moving my .Net Compact Framework application to the SD-card of a Windows CE device, the program executes slower then running it from the internal memory.
I thought, the start-up might be slower, but it is the whole program. There is no IO to the storage card.
Why is my application so slow and how does the compac... | It has to do with demand-paging. Your app cannot be run directly from the SD-card, as SD is not executable media so it has to be pulled into RAM to run. Windows CE doesn't typically have a whole lot of RAM, so the loader doesn't pull your entire application into RAM to run. Sure, your heaps and stacks will be in RAM, b... | I agree with the previous "demand-paging" answer by ctacke.
**A solution** you might try is to execute a loader program from the SD-card that copies your actual executable and DLLs from card to hard disk, and then execute your program from the loader. In subsequent executions the loader can detect if the hard disk ver... | Why are my programs running from my SD card so slow? | [
"",
"c#",
"performance",
"compact-framework",
"sd-card",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.