Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
### Duplicate:
> [Difference between events and delegates and its respective applications](https://stackoverflow.com/questions/563549/difference-between-events-and-delegates-and-its-respective-applications)
>
> [What are the advantages of delegates?](https://stackoverflow.com/questions/639320/what-are-the-advantages-of-delegates)
>
> [Where do I use delegates?](https://stackoverflow.com/questions/31497/where-do-i-use-delegates)
I wonder what the purpose of delegates is. I haven't used them that much and can't really think of something.
In my courses, it's written that a delegate is a blue-print for all methods that comply with its signature.
Also, you can add multiple methods to one delegate, and then they'll be executed after eachother in the order they were added. Which is probably only usefull for methods that affect local variables or methodes that don't return any values.
I've read that C# implements Events as delegates, which is documented as being:
```
//Summary: Represents the method that
will handle an event that has no event
data.
//Parameters:
//sender: The source of the event.
//e: An System.EventArgs that contains no event data.
[Serializable]
[ComVisible(true)]
public delegate void EventHandler(object sender, EventArgs e);
```
Still, it's kinda confusing. Can someone give a good, usefull example of this concept? | Yeah,
You're almost there. A delegate refers to a method or function to be called. .NET uses the Events to say.. when someones presses this button, I want you to execute this piece of code.
For example, in the use of a GPS application:
```
public delegate void PositionReceivedEventHandler(double latitude, double longitude);
```
This says that the method must take two doubles as the inputs, and return void. When we come to defining an event:
```
public event PositionReceivedEventHandler PositionReceived;
```
This means that the PositionRecieved event, calls a method with the same definition as the
PositionReceivedEventHandler delegate we defined. So when you do
```
PositionRecieved += new PositionReceivedEventHandler(method_Name);
```
The method\_Name must match the delegate, so that we know how to execute the method, what parameters it's expecting. If you use a Visual Studio designer to add some events to a button for example, it will all work on a delegate expecting an object and an EventArgs parameter.
Hope that helps some... | As you noted a delegate is a way to create a signature for an method call. There are many great examples of using delegates, but the one that really opened my mind is this example.
```
public delegate Duck GetDuckDelegate();
public GetDuckDelegate GiveMeTheDuckFactoryMethod(string type)
{
switch(type)
{
case "Rubber":
return new GetDuckDelegate(CreateRubberDuck);
case "Mallard":
return new GetDuckDelegate(CreateMallardDuck);
default:
return new GetDuckDelegate(CreateDefaultDuck);
}
}
public Duck CreateRubberDuck()
{
return new RubberDuck();
}
public Duck CreateMallardDuck()
{
return new MallardDuck();
}
public Duck CreateDefaultDuck()
{
return new Duck();
}
```
Then to use it
```
public static void Main() {
var getDuck = GiveMeTheDuckFactoryMethod("Rubber");
var duck = getDuck();
}
```
Arguably, the Factory pattern would be a better method for this, but I just thought up this example on the fly and thought it proved the point of how delegates can be treated as objects | The purpose of delegates | [
"",
"c#",
".net",
"delegates",
""
] |
I would like to generate the following select statement dynamically using expression trees:
```
var v = from c in Countries
where c.City == "London"
select new {c.Name, c.Population};
```
I have worked out how to generate
```
var v = from c in Countries
where c.City == "London"
select new {c.Name};
```
but I cannot seem to find a constructor/overload that will let me specify multiple properties in my select lambda. | This can be done, as mentioned, with the help of Reflection Emit and a helper class I've included below. The code below is a work in progress, so take it for what it's worth... 'it works on my box'. The SelectDynamic method class should be tossed in a static extension method class.
As expected, you won't get any Intellisense since the type isn't created until runtime. Works good on late-bound data controls.
```
public static IQueryable SelectDynamic(this IQueryable source, IEnumerable<string> fieldNames)
{
Dictionary<string, PropertyInfo> sourceProperties = fieldNames.ToDictionary(name => name, name => source.ElementType.GetProperty(name));
Type dynamicType = LinqRuntimeTypeBuilder.GetDynamicType(sourceProperties.Values);
ParameterExpression sourceItem = Expression.Parameter(source.ElementType, "t");
IEnumerable<MemberBinding> bindings = dynamicType.GetFields().Select(p => Expression.Bind(p, Expression.Property(sourceItem, sourceProperties[p.Name]))).OfType<MemberBinding>();
Expression selector = Expression.Lambda(Expression.MemberInit(
Expression.New(dynamicType.GetConstructor(Type.EmptyTypes)), bindings), sourceItem);
return source.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Select", new Type[] { source.ElementType, dynamicType },
Expression.Constant(source), selector));
}
public static class LinqRuntimeTypeBuilder
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static AssemblyName assemblyName = new AssemblyName() { Name = "DynamicLinqTypes" };
private static ModuleBuilder moduleBuilder = null;
private static Dictionary<string, Type> builtTypes = new Dictionary<string, Type>();
static LinqRuntimeTypeBuilder()
{
moduleBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run).DefineDynamicModule(assemblyName.Name);
}
private static string GetTypeKey(Dictionary<string, Type> fields)
{
//TODO: optimize the type caching -- if fields are simply reordered, that doesn't mean that they're actually different types, so this needs to be smarter
string key = string.Empty;
foreach (var field in fields)
key += field.Key + ";" + field.Value.Name + ";";
return key;
}
public static Type GetDynamicType(Dictionary<string, Type> fields)
{
if (null == fields)
throw new ArgumentNullException("fields");
if (0 == fields.Count)
throw new ArgumentOutOfRangeException("fields", "fields must have at least 1 field definition");
try
{
Monitor.Enter(builtTypes);
string className = GetTypeKey(fields);
if (builtTypes.ContainsKey(className))
return builtTypes[className];
TypeBuilder typeBuilder = moduleBuilder.DefineType(className, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable);
foreach (var field in fields)
typeBuilder.DefineField(field.Key, field.Value, FieldAttributes.Public);
builtTypes[className] = typeBuilder.CreateType();
return builtTypes[className];
}
catch (Exception ex)
{
log.Error(ex);
}
finally
{
Monitor.Exit(builtTypes);
}
return null;
}
private static string GetTypeKey(IEnumerable<PropertyInfo> fields)
{
return GetTypeKey(fields.ToDictionary(f => f.Name, f => f.PropertyType));
}
public static Type GetDynamicType(IEnumerable<PropertyInfo> fields)
{
return GetDynamicType(fields.ToDictionary(f => f.Name, f => f.PropertyType));
}
}
``` | The accepted answer is very useful, but I needed something a little closer to a real anonymous type.
A real anonymous type has read-only properties, a constructor for filling in all of the values, an implementation of Equals/GetHashCode for comparing the values of each property, and an implementation ToString that includes the name/value of each property. (See <https://msdn.microsoft.com/en-us/library/bb397696.aspx> for a full description of anonymous types.)
Based on that definition of anonymous classes, I put a class that generates dynamic anonymous types on github at <https://github.com/dotlattice/LatticeUtils/blob/master/LatticeUtils/AnonymousTypeUtils.cs>. The project also contains some unit tests to make sure the fake anonymous types behave like real ones.
Here's a very basic example of how to use it:
```
AnonymousTypeUtils.CreateObject(new Dictionary<string, object>
{
{ "a", 1 },
{ "b", 2 }
});
```
Also, another note: I found that when using a dynamic anonymous type with Entity Framework, the constructor must be called with the "members" parameter set. For example:
```
Expression.New(
constructor: anonymousType.GetConstructors().Single(),
arguments: propertyExpressions,
members: anonymousType.GetProperties().Cast<MemberInfo>().ToArray()
);
```
If you used one of the versions of Expression.New that does not include the "members" parameter, Entity Framework would not recognize it as the constructor of an anonymous type. So I assume that means a real anonymous type's constructor expression would include that "members" information. | How to create LINQ Expression Tree to select an anonymous type | [
"",
"c#",
"linq",
"entity-framework",
"linq-to-entities",
"expression-trees",
""
] |
I used a Select() to perform a calculation on each member of an array of structs and now want to have the member for which a certain attribute is minimal. I wanted to use something like Min() on the selected sequence, but I don't know how to return the full struct, rather than only the attribute that is minmal. | How about ordering by your "value" and taking the first entry (the minimum value):
```
Persons.OrderBy(p => p.Age).FirstOrDefault();
```
That is of course if you only want **one** item (which is what you state).
Alternatively:
```
from p in Persons
where p.Age == Persons.Select(p1 => p1.Age).Min()
select p;
```
Will get you all items with minimum value. | Sounds like you want to use [`MinBy`](http://code.google.com/p/morelinq/source/browse/trunk/MoreLinq/Pull/Aggregation.cs) from [MoreLINQ](http://code.google.com/p/morelinq/):
```
public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
source.ThrowIfNull("source");
selector.ThrowIfNull("selector");
comparer.ThrowIfNull("comparer");
using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
throw new InvalidOperationException("Sequence was empty");
}
TSource min = sourceIterator.Current;
TKey minKey = selector(min);
while (sourceIterator.MoveNext())
{
TSource candidate = sourceIterator.Current;
TKey candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, minKey) < 0)
{
min = candidate;
minKey = candidateProjected;
}
}
return min;
}
}
```
`ThrowIfNull` is defined as an extension method:
```
internal static void ThrowIfNull<T>(this T argument, string name)
where T : class
{
if (argument == null)
{
throw new ArgumentNullException(name);
}
}
``` | Minimum of a struct-Array in C# | [
"",
"c#",
""
] |
I know there is not a direct way to take a screen shot of a web page with PHP. What would be the most straightforward way to accomplish this? Are there any command line tools that could do this that I might be able to execute from a PHP script (I'm thinking something that would run in a 'NIX OS (OS X and/or Linux in particular)?
Edit: Or maybe some sort of web service I could access via SOAP or REST or ...
Edit #2: I found a [related question](https://stackoverflow.com/questions/125951/command-line-program-to-create-website-screenshots-on-linux) discussing the CLI option, but I'd still be open to other methods if anyone knows of anything. | See [webkit2png](http://www.paulhammond.org/webkit2png/) for an OSX commandline program that does this.
The page also mentions Linux alternatives.
[edit]: [wkhtml2image](http://code.google.com/p/wkhtmltopdf/downloads/list) is the newest kid in town, and it works better then anything else i've ever used.
[edit2]: As of 2014, [PhantomJS](http://phantomjs.org/screen-capture.html) seems to be the way to go, as it has the newest webkit version of the alternatives I know about.
[edit3]: In 2019, [Puppeteer](https://github.com/GoogleChrome/puppeteer) is the way to go. Official headless chrome, always up to date. | You can use the GD functions [`imagegrabscreen()`](http://www.php.net/imagegrabscreen) or [`imagegrabwindow()`](http://www.php.net/imagegrabwindow) to take a screenshot, but they're only available on Windows at the moment. | Web Page Screenshots with PHP? | [
"",
"php",
"unix",
"command-line",
"screenshot",
""
] |
Trying to get MVC running on Mono 2.4 (which is possible, according to some threads here) without much luck. I can't get past this:
```
Compilation Error
Description: Error compiling a resource required to service this request. Review your source file and modify it to fix this error.
Compiler Error Message: : ** (/usr/local/lib/mono/2.0/gmcs.exe:5232): WARNING **: The class System.Web.Management.WebRequestErrorEvent could not be loaded, used in System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
~/Global.asax
Show Detailed Compiler Output: //etc
```
I've added System.Web.dll (and literally every reference in the project) to the bin folder - still no go.
Any ideas?
LINKS:
Miguel de Icaza saying it's possible: [Twitter](http://explore.twitter.com/migueldeicaza/status/1351409209)
[SO 1](https://stackoverflow.com/questions/678212/asp-net-mvc-on-mono-2-2)
[SO 2](https://stackoverflow.com/questions/202430) | You shouldn't need to compile MVC (or Mono), but you will need at Mono 2.4, which is available on the Mono download site.
The only DLL you need is the System.Web.Mvc.dll. The easiest way to handle this in VS would be to set "Copy Local" to true for that assembly. Don't copy local any of the other System.\* references. | What about any DLLs that System.Web references. | ASP.NET MVC 1.0 + Mono 2.4 | [
"",
"c#",
"asp.net-mvc",
"mono",
""
] |
I have the following T-SQL in a `SelectCommand`:
```
SELECT h.Business,
hrl.frn
FROM registration hrl
INNER JOIN holder h on h.call = hrl.call
WHERE
(h.Business like '%' + @business + '%' and h.Business is not null)
and
(hrl.frn = @frn and hrl.frn is not null)
```
`business` and `frn` are tied to control parameters and it should return data even if one or both is left blank, but if I put in data just for `frn` for example, it does not return anything. I think my T-SQL is not doing the right thing and I am also not sure if I am handling the `like` correctly.
if both textboxes are left empty, it should return all data. If `frn` is entered, but `business` is left blank, it should only return data related to that `frn`. If `business` if entered, but `frn` is left blank, it should return all matches `like` `business`. If both are entered, it should return data only matching the `frn` and the `business`.
Also, I am not sure if doing the `and is not null` is actually necessary.
```
protected void btnSearch_Click(object sender, EventArgs e)
{
if (txtFRN.Text == "")
frn = null;
if (txtBusiness.Text == "")
business = null;
sqlDsMaster.SelectParameters[frn].DefaultValue = frn;
sqlDsMaster.SelectParameters[business].DefaultValue = business;
sqlDsMaster.DataBind();
}
```
The above throws an "Object Reference not set to an instance" when it hits this line:
```
sqlDsMaster.SelectParameters[frn].DefaultValue = frn;
```
`frn` and `business` are properties.
---
Here is the `SearchMaster` stored procedure:
```
CREAETE PROCEDURE SearchMaster
@business nvarchar(300) = NULL,
@frn nvarchar(10) = NULL
AS
SELECT h.Business,
hrl.frn
FROM registration hrl
INNER JOIN holder h on h.call = hrl.call
WHERE (@business IS NULL OR h.Business like '%' + @business + '%')
AND (@frn IS NULL OR hrl.frn = @frn)
```
Here is the `SearchDetails` stored procedure:
```
CREATE PROCEDURE SearchDetails
@business nvarchar(300) = NULL,
@frn nvarchar(10) = NULL
AS
SELECT hrl.call
FROM registration hrl
INNER JOIN holder h ON h.call = hrl.call
WHERE (@business IS NULL OR h.Business LIKE '%' + @business + '%')
AND (@frn IS NULL OR hrl.frn = @frn)
```
Here is the `SqlDataSource` for the `SearchMaster` procedure:
```
<asp:SqlDataSource ID="sqlDsDetails"
runat="server"
ConnectionString="<%$ ConnectionStrings:cnxString %>
SelectCommandType="StoredProcedure"
SelectCommand="SearchMaster">
<SelectParameters>
<asp:ControlParameter Name="business" ControlID="txtBusiness"
Type="String" PropertyName="Text"
ConvertEmptyStringToNull="true" />
<asp:ControlParameter Name="frn" ControlID="txtFRN"
Type="String" PropertyName="Text"
ConvertEmptyStringToNull="true"/>
</SelectParameters>
</asp:SqlDataSource>
```
Here is the `SqlDataSource` for the `SearchDetails` procedure:
```
<asp:SqlDataSource ID="sqlDsDetails"
runat="server"
ConnectionString="<%$ ConnectionStrings:cnxString %>
SelectCommandType="StoredProcedure"
SelectCommand="SearchDetails">
<SelectParameters>
<asp:Parameter Name="frn" Type="String" DefaultValue=""
ConvertEmptyStringToNull="true" />
<asp:Parameter Name="business" Type="String" DefaultValue=""
ConvertEmptyStringToNull="true" />
</SelectParameters>
</asp:SqlDataSource>
```
Here is the button click that binds the `SqlDsMaster`:
```
protected void btnSearch_Click(object sender, EventArgs e)
{
sqlDsMaster.DataBind();
}
```
Here is the `gvMaster_RowCreated` that creates the rows for the details:
```
protected void gvMaster_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlDataSource ctrl =
e.Row.FindControl("sqlDsDetails") as SqlDataSource;
if (ctrl != null && e.Row.DataItem != null)
{
ctrl.SelectParameters["frn"].DefaultValue =
((DataRowView)e.Row.DataItem)["frn"].ToString();
ctrl.SelectParameters["business"].DefaultValue =
((DataRowView)e.Row.DataItem)["business"].ToString();
}
}
}
```
`SearchMaster` and `SearchDetails` both work if I run it through SQL Server Management Studio and it works if I enter both data for `business` and `frn`, but if I enter just one, no data is returned. Are the parameters set up correctly? Also, if I am initializing the parameters to `null` in the procedure, is it still necessary to use `ConvertEmptyStringToNull`? | I would do something like:
```
where (@business is null
or @business = ''
or h.Business like '%' + @business + '%')
and (@frn is null
or @frn = ''
or hrl.frn = @frn)
```
If you make your empty search strings nulls before passing them, you can skip the @yyy = '' part. | Change
"and h.Business is not null"
to
"or h.Business is null"
and
"and hrl.frn is not null"
to
"or hrl.frn is null"
That will return everything when those parameters are null. | SqlDataSource SelectCommand using LIKE does not work | [
"",
"c#",
"asp.net",
"t-sql",
"sqldatasource",
""
] |
I want to make a component to occupy the maximumAvailableHeight of the Container. In the code that I have pasted below for example, I have made the root frame to be 800,600. I want to set the height/width of only that frame (and I do not want to try and pixelify its children). If I run this, I see a badly aligned UI.
Firstly, I want a panel (that is inside the root frame) to take up the 100% height of frame (in this case 800px minus that little space it takes for painting the frame title).
Secondly, inside the panel I have a tree and text area. I want both of them to take 100% height and let the tree take 30% and textArea take 70% width (if the tree is expanded to 10 levels then I am ok with ScrollPane).
Understand that this is easiest to achieve in HTML. Just say height=100% and width to be 30% etc and we are done. Does someone know if this can be done in Swing? (I can achieve this by setting pixel heights and layout manager but I am looking for the cleanest solution to set percentage heights and widths.)
```
package com.ekanathk.logger.gui;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TestFrame extends JFrame {
public TestFrame() {
super("Top Frame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTree env = getEnvironmentTree();
env.expandRow(0);
panel.add(new JScrollPane(env));
panel.add(new JTextArea("Some contents"));
getContentPane().add(panel);
setSize(800, 600);
SwingUtil.centerComponentOnScreen(this);
setVisible(true);
}
private JTree getEnvironmentTree() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
JTree tree = new JTree(root);
DefaultMutableTreeNode one = new DefaultMutableTreeNode("One");
root.add(one);
one.add(new DefaultMutableTreeNode("under one.1"));
one.add(new DefaultMutableTreeNode("under one.2"));
root.add(new DefaultMutableTreeNode("two"));
root.add(new DefaultMutableTreeNode("three"));
return tree;
}
public static void main(String[] args) {
new TestFrame();
}
}
``` | This uses GridBagLayout to do sort of what you want. You might play around with setMinimumSize and setPreferedSize of your components.
```
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
public TestFrame() {
super("Top Frame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
JTree env = getEnvironmentTree();
env.expandRow(0);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx=.7;
c.weighty=1;
c.gridx=0;
c.gridy=0;
c.gridheight=1;
c.gridwidth=7;
panel.add(new JScrollPane(env),c);
c.weightx=.3;
c.gridx=7;
c.gridy=0;
c.gridheight=1;
c.gridwidth=GridBagConstraints.REMAINDER;
panel.add(new JTextArea("Some contents"),c);
add(panel);
setSize(800, 600);
setLocationRelativeTo(null);
setVisible(true);
}
private JTree getEnvironmentTree() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
JTree tree = new JTree(root);
DefaultMutableTreeNode one = new DefaultMutableTreeNode("One");
root.add(one);
one.add(new DefaultMutableTreeNode("under one.1"));
one.add(new DefaultMutableTreeNode("under one.2"));
root.add(new DefaultMutableTreeNode("two"));
root.add(new DefaultMutableTreeNode("three"));
return tree;
}
public static void main(String[] args) {
new TestFrame();
}
}
``` | There are a number of [layout managers](http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html) that would accomplish this--GridLayout (1x1 grid), GridBagLayout, perhaps BorderLayout. | Swing: How do I set a component height to the container's height? | [
"",
"java",
"swing",
""
] |
More specifically, is there a set of values ( a, b and c) for which the operator precedence matters in the statement:
```
var value = (a && b == c);
```
(with the exception of NaN). | Yes
```
js> false && true == false
false
js> (false && true) == false
true
```
Since `==` has higher precedence than `&&`, the first is parsed as `false && (true == false)`, which is equivalent to `false && false`, and thus evaluates to `false`. The second is equivalent to `false == false`, which is `true` | The language is parsed such that your statement is the equivalent of `(a && (b == c))`. The equality operator will always run before `&&`, `||` and other logical operators. You can find the nitty-gritty details [here](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Operator_Precedence). | Does operator precedence matter for && and == in javascrtipt? | [
"",
"javascript",
"operators",
"operator-precedence",
""
] |
> Since this question is rather popular, I thought it useful to give it an update.
>
> Let me emphasise **the correct answer** as given by [AviD](https://security.stackexchange.com/users/33/avid) to this question:
>
> **You should not store any data that needs encrypting in your cookie.** Instead, store a good sized (128 bits/16 bytes) random key in the cookie and store the information you want to keep secure on the server, identified by the cookie's key.
---
I'm looking for information about 'the best' encryption algorithm for encrypting cookies.
I hava the following requirements:
* It must be fast
* It will operate on small data sets, typically strings of around 100 character or less
* It must be secure, but it's not like we're securing banking transactions
* We need to be able to decrypt the information so SHA1 and the like are out.
Now I've read that Blowfish is fast and secure, and I've read that AES is fast and secure.
With Blowfish having a smaller block size.
I think that both algorithms provide more than adequate security? so the speed would then become the decisive factor.
But I really have no idea if those algorithm are suited for small character string and if there are maybe better suited algorithm for encrypting cookies.
**So my question is:**
**Update**
To be more precise, we want to encrypt 2 cookie: one with session information and the other with 'remeber me' information.
The platform is PHP as apache module on Linux on a VPS.
**Update 2**
I agree with [cletus](https://stackoverflow.com/users/18393/cletus) that storing any information in a cookie is insecure.
However, we have a requirement to implement a 'remeber me' feature. The accepted way to go about this is by setting a cookie. If the client presents this cookie, he or she is allowed access the system with (almost) equal rights as if he/she presented the valid username password combination.
So we at least want to encrypt all data in the cookie so that it:
**a)** malicious users can't read it's contents,
**b)** malicious users can't fabricate their own cookie or tamper with it.
(All data from cookies is sanitized and checked for validity before we do anything with it, but that's another story)
The session cookie contains a sessionId/timestamp nothing more. It could probably be used without encryption, but I see no harm in encrypting it? (other than computation time).
*So given that we have to store some data on in a cookie, what is the best way to encrypt it?*
**Update 3**
The responses to this question made me reconsider the chosen approach. I can indeed do the same without the need for encryption. Instead of encrypting the data, I should only send out data that is meaningless without it's context *and cannot be guessed*.
*However, I'm also at a loss:*
I thought that encryption enabled us send data out in to the BigBadWorld™, and still be (fairly) sure that nobody could read or tamper with the it...
Wasn't that the whole point of encryption?
But the reactions below push toward: Do not trust encryption to accomplish security.
*What am I missing??* | No real reason not to go with [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) with 256 bits. Make sure to use this in [CBC mode](http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29), and PKCS#7 padding.
As you said, fast and secure.
I have read (not tested) that Blowfish may be marginally faster... However Blowfish has a major drawback of long setup time, which would make it bad for your situation. Also, AES is more "proven".
This assumes that it really *is* necessary to symmetrically encrypt your cookie data. As others have noted, it really shouldnt be necessary, and there are only a few edge cases where there's no other choice but to do so. Commonly, it would better suit you to change the design, and go back to either random session identifiers, or if necessary one-way hashes (using SHA-256).
In your case, besides the "regular" random session identifier, your issue is the "remember me" feature - this should also be implemented as either:
* a long random number, stored in the database and mapped to a user account;
* or a keyed hash (e.g. HMAC) containing e.g. the username, timestamp, mebbe a salt, AND a secret server key. This can of course all be verified server-side...
Seems like we've gotten a little off topic of your original, specific question - and changed the basis of your question by changing the design....
So as long as we're doing that, I would also STRONGLY recommend *AGAINST* this feature of persistent "remember me", for several reasons, the biggest among them:
* Makes it much more likely that someone may steal that user's remember key, allowing them to spoof the user's identity (and then probably change his password);
* [CSRF](http://www.cgisecurity.com/csrf-faq.html) - [Cross Site Request Forgery](http://www.owasp.org/index.php/Cross-Site_Request_Forgery). Your feature will effectively allow an anonymous attacker to cause unknowing users to submit "authenticated" requests to your application, even without being actually logged in. | This is touching on two separate issues.
Firstly, **session hijacking**. This is where a third party discovers, say, an authenticated cookie and gains access to someone else's details.
Secondly, there is **session data security**. By this I mean that you store data in the cookie (such as the username). This is not a good idea. Any such data is fundamentally untrustworthy just like HTML form data is untrustworthy (irrespective of what Javascript validation and/or HTML length restrictions you use, if any) because a client is free to submit what they want.
You'll often find people (rightly) advocating sanitizing HTML form data but cookie data will be blindly accepted on face value. Big mistake. In fact, I never store any information in the cookie. I view it as a session key and that's all.
**If you intend to store data in a cookie I strongly advise you to reconsider.**
Encryption of this data does not make the information any more trustworth because symmetric encryption is susceptible to brute-force attack. Obviously AES-256 is better than, say, DES (heh) but 256-bits of security doesn't necessarily mean as much as you think it does.
For one thing, SALTs are typically generated according to an algorithm or are otherwise susceptible to attack.
For another, cookie data is a prime candidate for [crib](http://en.wikipedia.org/wiki/Crib_(cryptanalysis)) attacks. If it is known or suspected that a username is in the encrypted data will hey, there's your crib.
This brings us back to the first point: hijacking.
It should be pointed out that on shared-hosting environments in PHP (as one example) your session data is simply stored on the filesystem and is readable by anyone else on that same host although they don't necessarily know which site it is for. So never store plaintext passwords, credit card numbers, extensive personal details or anything that might otherwise be deemed as sensitive in session data in such environments without some form of encryption or, better yet, just storing a key in the session and storing the actual sensitive data in a database.
**Note:** the above is not unique to PHP.
But that's server side encryption.
Now you could argue that encrypting a session with some extra data will make it more secure from hijacking. A common example is the user's IP address. Problem is many people use the same PC/laptop at many different locations (eg Wifi hotspots, work, home). Also many environments will use a variety of IP addresses as the source address, particularly in corporate environments.
You might also use the user agent but that's guessable.
So really, as far as I can tell, there's no real reason to use cookie encryption at all. I never did think there was but in light of this question I went looking to be proven either right or wrong. I found a few threads about people suggesting ways to encrypt cookie data, transparently do it with Apache modules, and so on but these all seemed motivated by protecting data stored in a cookie (which imho you shouldn't do).
I've yet to see a security argument for encrypting a cookie that represents nothing more than a session key.
I will happily be proven wrong if someone can point out something to the contrary. | What encryption algorithm is best for encrypting cookies? | [
"",
"php",
"security",
"cookies",
"encryption",
"remember-me",
""
] |
I captured the standard output of an external program into a `bytes` object:
```
>>> from subprocess import *
>>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>> stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
```
I want to convert that to a normal Python string, so that I can print it like this:
```
>>> print(stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
```
How do I convert the `bytes` object to a `str` with Python 3?
---
See [Best way to convert string to bytes in Python 3?](https://stackoverflow.com/questions/7585435) for the other way around. | [Decode the `bytes` object](https://docs.python.org/3/library/stdtypes.html#bytes.decode) to produce a string:
```
>>> b"abcde".decode("utf-8")
'abcde'
```
The above example *assumes* that the `bytes` object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in! | Decode the byte string and turn it in to a character (Unicode) string.
---
Python 3:
```
encoding = 'utf-8'
b'hello'.decode(encoding)
```
or
```
str(b'hello', encoding)
```
---
Python 2:
```
encoding = 'utf-8'
'hello'.decode(encoding)
```
or
```
unicode('hello', encoding)
``` | Convert bytes to a string in Python 3 | [
"",
"python",
"string",
"python-3.x",
""
] |
I ran across a class that was set up like this:
```
public class MyClass {
private static boolean started = false;
private MyClass(){
}
public static void doSomething(){
if(started){
return;
}
started = true;
//code below that is only supposed to run
//run if not started
}
}
```
My understanding with static methods is that you should not use class variables in them unless they are constant, and do not change. Instead you should use parameters. My question is why is this not breaking when called multiple times by doing MyClass.doSomething(). It seems to me like it should not work but does. It will only go pass the if statement once.
So could anyone explain to me why this does not break? | The method `doSomething()` and the variable `started` are both static, so there is only one copy of the variable and it is accessible from `doSomething()`. The first time `doSomething()` is called, `started` is false, so it sets `started` to true and then does... well, something. The second and subsequent times it's called, `started` is true, so it returns without doing anything. | There's no reason why using a static variable wouldn't work. I'm not saying it's particularly good practice, but it will work.
What should happen is:
1. The first call is made. The class is initialised, started is false.
2. doSomething is called. The if fails and the code bypasses it. started is set to true and the other code runs.
3. doSomething is called again. The if passes and execution stops.
The one thing to note is that there is no synchronization here, so if doSomething() was called on separate threads incredibly close together, each thread could read started as false, bypass the if statement and do the work i.e. there is a race condition. | Static variables and methods | [
"",
"java",
"static-methods",
"static-members",
""
] |
I have an object that holds alerts and some information about them:
```
var alerts = {
1: { app: 'helloworld', message: 'message' },
2: { app: 'helloagain', message: 'another message' }
}
```
In addition to this, I have a variable that says how many alerts there are, `alertNo`. My question is, when I go to add a new alert, is there a way to append the alert onto the `alerts` object? | How about storing the alerts as records in an array instead of properties of a single object ?
```
var alerts = [
{num : 1, app:'helloworld',message:'message'},
{num : 2, app:'helloagain',message:'another message'}
]
```
And then to add one, just use `push`:
```
alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});
``` | You can do this with [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). Sometimes you need an array, but when working with functions that expect a single JSON object -- such as an OData call -- I've found this method simpler than creating an array only to unpack it.
```
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
alerts = Object.assign({3: {app:'helloagain_again',message:'yet another message'}}, alerts)
//Result:
console.log(alerts)
{
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
3: {app: "helloagain_again",message: "yet another message"}
}
```
EDIT: To address the comment regarding getting the next key, you can get an array of the keys with the [Object.keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) function -- see Vadi's answer for an example of incrementing the key. Similarly, you can get all the values with [Object.values()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) and key-values pairs with [Object.entries()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries).
```
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]
``` | Appending to an object | [
"",
"javascript",
""
] |
Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous [PEP8](http://www.python.org/dev/peps/pep-0008/), and made some research on google, and it seems that the accepted convention is to add the letter "s" at the end of the variable name.
Let's assume we have a sequence of "weight values", therefore the variable name for the sequence should be *weights*. So far that's fine, but there will be cases where some word ends with "s" and happen to be the more logical way to name a variable which is not a sequence. Or let's say you have sequences of weights themselves stored into a sequence. The "s" naming convention would name the variable *weightss*, which is ugly. I am sure there is be a better naming convention for sequences.
What naming convention for sequences would you advise? | In general, avoid this kind of behaviour. Notice from [PEP8](http://www.python.org/dev/peps/pep-0008/)
> A Foolish Consistency is the Hobgoblin
> of Little Minds
which is exactly what calling a variable `weightss` would be doing. So in general have your variables describing what they are, not according to some naming convention:
```
weights = [44, 66, 88]
weight_groups = [[44, 66, 88], ...]
```
etc.
From the same section of the [PEP8](http://www.python.org/dev/peps/pep-0008/):
> But most importantly: know when to be
> inconsistent -- sometimes the style
> guide just doesn't apply. When in
> doubt, use your best judgment. Look
> at other examples and decide what
> looks best. And don't hesitate to
> ask! | > The "s" naming convention would name the variable weightss, which is ugly. I am sure there is be a better naming convention for sequences.
I think the convention you're describing is meant to be interpreted as "whenever you have list of something, make it clear that it's a list by pluralizing it". For example, if you have a list of instances of grass, you would call this `grasses`, not `grasss`. I don't think it's meant to be taken as literally as you're taking it.
PEP always advises you to take your own approach if that is more readable and useful. As [**Ali mentioned**](https://stackoverflow.com/questions/659415/python-sequence-naming-convention/659439#659439), one of the guiding principles of PEP is that you shouldn't fall prey to foolish consistencies. | Python sequence naming convention | [
"",
"python",
"naming-conventions",
"sequence",
""
] |
In the MSDN article [Understanding Routed Events and Commands In WPF](http://msdn.microsoft.com/en-us/magazine/cc785480.aspx), it states
> *an event will bubble (propagate) up the visual tree from the source element until either it has been handled or it reaches the root element.*
However, in this example, when you click the button, **it doesn't "bubble up the visual tree" to get handled by the parent StackPanel event**, i.e. clicking on the button fires no event.
Why not? **What do they mean then by "bubbling up"** if not this?
**XAML:**
```
<Window x:Class="TestClickEvents456.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel x:Name="TheStackPanel"
Background="Yellow"
MouseDown="TheStackPanel_MouseDown">
<Button x:Name="TheButton"
Margin="10"
Content="Click This"/>
<TextBlock x:Name="TheMessage"
Text="Click the button or the yellow area"/>
</StackPanel>
</Window>
```
**code-behind:**
```
using System.Windows;
using System.Windows.Input;
namespace TestClickEvents456
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void TheStackPanel_MouseDown(object sender, MouseButtonEventArgs e)
{
TheMessage.Text = "StackPanel was clicked.";
}
}
}
``` | The event bubbles up, until it gets handled...
Since the Button does something with your mouse clicks, it absorbs your mouse event and turns it into a ClickEvent.
If you use the PreviewMouseDown, you see that the StackPanel first receives the event before the button does.. Preview events use the Tunnel down approach.. | As others have said, it's because the `MouseDown` event gets handled by the `Button` before it can be bubbled further. You can see this in Reflector, in `ButtonBase.OnMouseLeftButtonDown`:
```
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (this.ClickMode != ClickMode.Hover)
{
e.Handled = true;
// SNIP...
}
base.OnMouseLeftButtonDown(e);
}
```
One solution is to listen for a `MouseDown` event, and indicate that you don't care if the event is handled. You can do this with the [`AddHandler`](http://msdn.microsoft.com/en-us/library/ms598899.aspx) method. It has a boolean overload that lets you listen for events which are already handled.
If you do this somewhere instead of setting the MouseDown handler in XAML:
```
TheStackPanel.AddHandler(MouseDownEvent, new MouseButtonEventHandler(TheStackPanel_MouseDown), true);
```
You'll receive all `MouseDown` events on `TheStackPanel`, regardless of whether they've been handled. | Why doesn't button click event "bubble up visual tree" to StackPanel as MSDN article states? | [
"",
"c#",
"wpf",
"event-routing",
""
] |
I need to run a query like:
```
SELECT p.id, p.name,
(SELECT name
FROM sites s
WHERE s.id = p.site_id) AS site_list
FROM publications p
```
But I'd like the sub-select to return a comma separated list, instead of a column of data. Is this even possible, and if so, how? | You can use [GROUP\_CONCAT](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) to perform that, e.g. something like
```
SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id, p.name;
``` | Now only I came across this situation and found some more interesting features around `GROUP_CONCAT`. I hope these details will make you feel interesting.
**simple GROUP\_CONCAT**
```
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
```
*Result:*
```
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
```
**GROUP\_CONCAT with DISTINCT**
```
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
```
*Result:*
```
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
```
**GROUP\_CONCAT with DISTINCT and ORDER BY**
```
SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC)
FROM Tasks;
```
*Result:*
```
+--------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) |
+--------------------------------------------------------+
| Take dog for walk,Relax,Paint roof,Feed cats,Do garden |
+--------------------------------------------------------+
```
**GROUP\_CONCAT with DISTINCT and SEPARATOR**
```
SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ')
FROM Tasks;
```
*Result:*
```
+----------------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') |
+----------------------------------------------------------------+
| Do garden + Feed cats + Paint roof + Relax + Take dog for walk |
+----------------------------------------------------------------+
```
**GROUP\_CONCAT and Combining Columns**
```
SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ')
FROM Tasks;
```
*Result:*
```
+------------------------------------------------------------------------------------+
| GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') |
+------------------------------------------------------------------------------------+
| 1) Do garden 2) Feed cats 3) Paint roof 4) Take dog for walk 5) Relax 6) Feed cats |
+------------------------------------------------------------------------------------+
```
**GROUP\_CONCAT and Grouped Results**
Assume that the following are the results before using `GROUP_CONCAT`
```
+------------------------+--------------------------+
| ArtistName | AlbumName |
+------------------------+--------------------------+
| Iron Maiden | Powerslave |
| AC/DC | Powerage |
| Jim Reeves | Singing Down the Lane |
| Devin Townsend | Ziltoid the Omniscient |
| Devin Townsend | Casualties of Cool |
| Devin Townsend | Epicloud |
| Iron Maiden | Somewhere in Time |
| Iron Maiden | Piece of Mind |
| Iron Maiden | Killers |
| Iron Maiden | No Prayer for the Dying |
| The Script | No Sound Without Silence |
| Buddy Rich | Big Swing Face |
| Michael Learns to Rock | Blue Night |
| Michael Learns to Rock | Eternity |
| Michael Learns to Rock | Scandinavia |
| Tom Jones | Long Lost Suitcase |
| Tom Jones | Praise and Blame |
| Tom Jones | Along Came Jones |
| Allan Holdsworth | All Night Wrong |
| Allan Holdsworth | The Sixteen Men of Tain |
+------------------------+--------------------------+
```
```
USE Music;
SELECT ar.ArtistName,
GROUP_CONCAT(al.AlbumName)
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;
```
*Result:*
```
+------------------------+----------------------------------------------------------------------------+
| ArtistName | GROUP_CONCAT(al.AlbumName) |
+------------------------+----------------------------------------------------------------------------+
| AC/DC | Powerage |
| Allan Holdsworth | All Night Wrong,The Sixteen Men of Tain |
| Buddy Rich | Big Swing Face |
| Devin Townsend | Epicloud,Ziltoid the Omniscient,Casualties of Cool |
| Iron Maiden | Somewhere in Time,Piece of Mind,Powerslave,Killers,No Prayer for the Dying |
| Jim Reeves | Singing Down the Lane |
| Michael Learns to Rock | Eternity,Scandinavia,Blue Night |
| The Script | No Sound Without Silence |
| Tom Jones | Long Lost Suitcase,Praise and Blame,Along Came Jones |
+------------------------+----------------------------------------------------------------------------+
``` | MySQL Results as comma separated list | [
"",
"sql",
"mysql",
"concatenation",
""
] |
We've just set up a new remote access solution using Microsoft's TS Gateway, which requires a couple of somewhat fiddly steps on the end users behalf in order to get it working (installing our root ca cert, requirement of RDP 6.1 client etc).
In order to make this setup process as easy as possible (a lot of these users aren't technically minded), I'm looking to create a program to perform all these tasks automatically. I have most of it working, however I'm not entirely sure how to go about importing the Root CA cert into the Windows certificate store.
Because this can potentially be run on a wide range of computers with varying levels of patches and updates, I'm steering well clear of .NET and anything that isn't native - the tool should 'just run' without the user having to install anything extra (well, I will say windows XP, no service packs, is the bare minimum required version of windows). In saying that, I don't mind using something third party if it can be bundled in with the tool, as long as it's not huge, and doesn't introduce any interactive steps. Ideally something in the windows API would be best, however I can't seem to track down anything relevant.
Currently the tool is a C++ application, so I don't mind if it's quite low level stuff. | First you need to open the root certificate store...
```
HCERTSTORE hRootCertStore = CertOpenSystemStore(NULL,"ROOT");
```
Then add the certificate using one of the CertAdd functions, such as CertAddEncodedCertificateToStore.
```
CertAddEncodedCertificateToStore(hRootCertStore,X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,pCertData,cbCertData,CERT_STORE_ADD_USE_EXISTING,NULL);
```
pCertData and cbCertData would likely point to the certificate data that you read from a file (not sure if the certificate will be in a file, or how you will include it in your application).
Then close the store with...
```
CertCloseStore(hRootCertStore,0);
```
NOTE: This code if run as the user, installs the certificate to the user's root store, not the computer's. It also results in a warning dialog that the user must understand and select "Yes" to authorize the import. If your setup program can run this code in a system account, the import will affect the computer's root store and not warning dialog will be shown. | Have you looked at [CertAddEncodedCertificateToStore](http://msdn.microsoft.com/en-us/library/aa376015(VS.85).aspx) ? | Installing Root CA Cert via code on Win32 | [
"",
"c++",
"winapi",
"certificate",
""
] |
I've got the following code:
```
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string a = "a";
for(unsigned int i=a.length()-1; i+1 >= 1; --i)
{
if(i >= a.length())
{
cerr << (signed int)i << "?" << endl;
return 0;
}
}
}
```
If I compile in MSVC with full optimizations, the output I get is "-1?". If I compile in Debug mode (no optimizations), I get no output (expected.)
I thought the standard guaranteed that unsigned integers overflowed in a predictable way, so that when i = (unsigned int)(-1), i+1 = 0, and the loop condition i + 1 >= 1 fails. Instead, the test is somehow passing. Is this a compiler bug, or am I doing something undefined somewhere? | I remember having this problem in 2001. I'm amazed it's still there. Yes, this is a compiler bug.
The optimiser is seeing
```
i + 1 >= 1;
```
Theoretically, we can optimise this by putting all of the constants on the same side:
```
i >= (1-1);
```
Because *i* is unsigned, it will always be greater than or equal to zero.
See this newsgroup discussion [here](http://groups.google.com/group/comp.lang.c++/browse_thread/thread/b1a20c37d5436bbf/729c5184d30299f7?q=%2B%22Andrew+Shepherd%22+%2B%22compiler+bug%22). | ISO14882:2003, section 5, paragraph 5:
> If during the evaluation of an expression, the result is not mathematically defined or *not in the range of representable values for its type*, the behavior is undefined, unless such an expression is a constant expression (5.19), in which case the program is ill-formed.
(Emphasis mine.) So, yes, the behavior is undefined. The standard makes no guarantees of behavior in the case of integer over/underflow.
Edit: The standard seems slightly conflicted on the matter elsewhere.
Section 3.9.1.4 says:
> Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2 n where n is the number of bits in the value representation of that particular size of integer.
But section 4.7.2 and .3 says:
> 2) If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2 n where n is the number of bits used to represent the unsigned type). [Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). ]
>
> 3) If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); *otherwise, the value is implementation-defined.*
(Emphasis mine.) | MSVC++: Strangeness with unsigned ints and overflow | [
"",
"c++",
"standards",
""
] |
I'm using a NotifyIcon control in one of my child (modal) forms and it is working fine. SHowing balloon tips as expected, handling mouse events etc... It doesn't however vanish when I would expect it to. Specifically, when i exit the child form and the parent is back in control the icon still remains. It's tooltip is accessible so it is very much "alive" as it were.
When I then exit my application as a whole the image still remains until the point i hover the cursor over it. Once moused it disappears.
How can I get it to behave normally? Ok normally is a bad word :-0 How can I get it to disappear when the form that created it disappears?
Could someone explain what is causing this as well, I thought .net was supposed to clean up after itself?
G
**EDIT:** If I call the Dispose method in the form closed evernt this works, but do I really have to do this? G | Here's a thought, not sure if this will make a difference, but are you calling Dispose() on the NotifyIcon when the child form closes?
EDIT: Just saw your edit, yes I'm not surprised that this helps, and yes you should do it. Under the covers something is using some unmanaged resourced, and you need to release it. Generally, anything in your app that implements IDisposable that you're using, do yourself a favor and Dispose it. | ```
Icon.Visible = false
```
would also work. Anyway, `Dispose` should still be called to dispose of the Windows handle. | How to guarantee a NotifyIcon disappears? | [
"",
"c#",
".net",
"winforms",
"dispose",
"notifyicon",
""
] |
I have the following code :
```
what = re.match("get|post|put|head\s+(\S+) ",data,re.IGNORECASE)
```
and in the **data** variable let's say I have this line :
```
GET some-site.com HTTP/1.0 ...
```
If I stop the script in the debugger, and inspect the **what** variable, I can see it only matched GET. Why doesn't it match some-site.com ? | ```
>>> re.match("(get|post|put|head)\s+(\S+) ",'GET some-site.com HTTP/1.0 ...',re.IGNORECASE).groups()
('GET', 'some-site.com')
>>>
``` | Regex language operator precedence puts `head\s+(\S+)` as the 4th alternative. The parenthesis in *@Mykola Kharechko*'s answer arrange for `head` as the 4th alternative, and `\s+(\S+)` is appended to whatever alternative matched the group. | python regex trouble | [
"",
"python",
"regex",
""
] |
I am using [SDL](http://www.libsdl.org/ "SDL") for an OpenGL application, running on Linux. My problem is that SDL is catching SIGINT and ignoring it. This is a pain because I am developing through a screen session, and I can't kill the running program with CTRL-C (the program the computer is running on is connected to a projector and has no input devices).
Is there a flag or something I can pass to SDL so that it does not capture SIGINT? I really just want the program to stop when it receives the signal (ie when I press ctrl-c). | Ctrl-C at the console generates an SDL\_QUIT event. You can watch for this event using SDL\_PollEvent or SDL\_WaitEvent, and exit (cleanly) when it is detected.
Note that other actions can generate an SDL\_QUIT event (e.g. attempting to close your main window via the window manager). | In SDL\_quit.c, there's a check for hints to determine whether the signal handlers should not be used in `SDL_QuitInit()`. Not sure if this existed in older versions when the original question was asked, but may be handy for those coming here fresh.
Just tested on my Windows application, I can now receive all signals properly again, using:
```
SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");
SDL_Init(...);
``` | SDL/C++ OpenGL Program, how do I stop SDL from catching SIGINT | [
"",
"c++",
"linux",
"signals",
"sdl",
""
] |
I have Business objects (DEVELOPERS WRITE) and some SPROCS (DBA WRITE)
Can anyone recommend a good object mapper to deal with this kind of setup.
I tried codesmith and nhibernate and had trouble. I do not mind if my ORM is free or paid. | SubSonic has excellent support for sprocs. It will wrap each one in a helper method and you can retrieve strongly-typed collections or entities from the results if you want. I show a way to do that in [this blog post](http://john-sheehan.com/blog/how-i-use-subsonic-part-1/). As long as your sproc returns the same schema as SELECT \* FROM TableName would, it will work with your SubSonic entities.
As far as generating classes based on your db, SubSonic generates partial classes so you can extend them as needed. You could also do mappings from the SubSonic generated classes to your actual model. | Disclaimer: I am the author of [Dapper](http://samsaffron.com/archive/2011/03/30/How+I+learned+to+stop+worrying+and+write+my+own+ORM).
---
If you are looking for a simple object mapper that handles mapping procs to business objects [Dapper](http://samsaffron.com/archive/2011/03/30/How+I+learned+to+stop+worrying+and+write+my+own+ORM) is a good fit.
Keep in mind it ships with no "graph management", "identity map" and so on. It offers a bare bone, **complete** solution which covers many scenarios other ORMs do not.
Nonetheless, it offers one of the fastest object materializers out there, which can be 10x faster than EF or even 100x faster than subsonic in some [benchmarks](http://samsaffron.com/archive/2011/03/30/How+I+learned+to+stop+worrying+and+write+my+own+ORM).
---
The trivial:
```
create proc spGetOrder
@Id int
as
select * from Orders where Id = @Id
select * from OrderItems where OrderId = @Id
```
Can be mapped with the following:
```
var grid = cnn.QueryMultiple("spGetOrder", new {Id = 1}, commandType: CommandType.StoredProcedure);
var order = grid.Read<Order>();
order.Items = grid.Read<OrderItems>();
```
Additionally you have support for:
1. A multi-mapper that allows you single rows to multiple objects
2. Input/Output/Return param support
3. An extensible interface for db specific parameter handling (like TVPs)
So for example:
```
create proc spGetOrderFancy
@Id int,
@Message nvarchar(100) output
as
set @Message = N'My message'
select * from Orders join Users u on OwnerId = u.Id where Id = @Id
select * from OrderItems where OrderId = @Id
return @@rowcount
```
Can be mapped with:
```
var p = new DynamicParameters();
p.Add("Id", 1);
p.Add("Message",direction: ParameterDirection.Output);
p.Add("rval",direction: ParameterDirection.ReturnValue);
var grid = cnn.QueryMultiple("spGetOrder", p, commandType: CommandType.StoredProcedure);
var order = grid.Read<Order,User,Order>((o,u) => {o.Owner = u; return o;});
order.Items = grid.Read<OrderItems>();
var returnVal = p.Get<int>("rval");
var message = p.Get<string>("message");
```
---
Finally, dapper also allow for a custom parameter implementation:
```
public interface IDynamicParameters
{
void AddParameters(IDbCommand command);
}
```
When implementing this interface you can tell dapper what parameters you wish to add to your command. This allow you to support Table-Valued-Params and other DB specific features. | Which ORM is the best when using Stored Procedures | [
"",
"c#",
".net",
"database",
"stored-procedures",
"orm",
""
] |
I've been trying to use CDT with Eclipse 3.4 under Windows XP with cygwin.
What do I need to do, in order to get startet?
I used "eclipse-cpp-ganymede-SR1-win32.zip" found on the Eclipse homepage.
Edit:
The main problem is, that I cannot compile and run the code.
In the run configuration, I tried gcc.exe for the C/C++ Application:
After adding the path of make.exe to my $Path, and starting from scratch, it works perfectly. | I finally found. Thanks guys.
After downloading and unpacking "eclipse-cpp-ganymede-SR1-win32.zip", you need to install either Cygwin or MinGW.
Make sure the compiler (e.g. gcc.exe) and make.exe is on your $Path.
Start Eclipse and everything should work fine. | If you want to use Eclipse/CDT on Windows, you should consider using [Wascana Desktop Developer](http://wascana.sourceforge.net/), a CDT distro specially targeting Windows hosts. | How to configure Eclipse with CDT? | [
"",
"c++",
"eclipse",
"cygwin",
"makefile",
"eclipse-cdt",
""
] |
How can I select `count(*)` from two different tables (call them `tab1` and `tab2`) having as result:
```
Count_1 Count_2
123 456
```
I've tried this:
```
select count(*) Count_1 from schema.tab1 union all select count(*) Count_2 from schema.tab2
```
But all I have is:
```
Count_1
123
456
``` | ```
SELECT (
SELECT COUNT(*)
FROM tab1
) AS count1,
(
SELECT COUNT(*)
FROM tab2
) AS count2
FROM dual
``` | As additional information, to accomplish same thing in SQL Server, you just need to remove the "FROM dual" part of the query. | Select count(*) from multiple tables | [
"",
"sql",
"oracle",
"count",
""
] |
Is it possible to start playing a file inside a flash player by making use of javascript code? If so, how would I do it? | Try using [swfObject](http://blog.deconcept.com/swfobject/), you can make any actionscript function visible for javascript using `ExternalInterface` and declaring them into javascript. So you can trigger actionscript function with `play()` (or any other code you want) from your javascript code.
Here is an example:
Actionscript:
```
import flash.external.ExternalInterface;
ExternalInterface.addCallback( "methodName", this, method );
function method() {
trace("called from javascript");
}
```
Javascript:
```
function callAS() {
swf.methodName();
}
```
Where methodName is the identifier js uses to call the method from actionscript. | Take a look at [SWFObject](http://blog.deconcept.com/swfobject/). There a lot of examples on how to accomplish that. | How can I start a flash video from javascript? | [
"",
"javascript",
"flash",
"playback",
""
] |
I'm having a hard time picking up how to grab the dimensions of an element with jQuery. Here is my sample code:
```
$(document).ready(function() {
var width = $("#image_1").width();
var height = $("#image_1").height();
document.write(width);
document.write(height);
});
```
Now of course I have an image with an id of #image\_1. What happens when I try to run it is that it outputs two zeros. Not null twice, or undefined twice.
Thanks for the help from a javascript newb. | This works for me:
```
<head>
<script type="text/javascript">
function foo() {
var image = document.getElementById("the_image");
alert(image.offsetWidth);
alert(image.offsetHeight);
}
</script>
</head>
<body onload="foo();">
<img src="img.png" id="the_image">
</body>
```
This works as long as the image is not set to `display: none;` Using `offsetWidth` and `offsetHeight` also has the advantage of not requiring jQuery, at all. | Even though you've already chosen an answer, I am typing this one so you understand why your prior code did not work.
jQuery's document.ready function fires before images are loaded. Use window.load instead...
```
$(window).load(function() {
var width = $("#image_1").width();
var height = $("#image_1").height();
document.write(width);
document.write(height);
});
```
For what it's worth, I think it is better to use jQuery for this task because of the inherent cross-browser functionality. | Having problems with grabbing image dimensions with jQuery | [
"",
"asp.net",
"javascript",
"jquery",
"css",
""
] |
Could someone please point me to a good beginner guide on safely running SQL queries formed partly from user input? I'm using Java, but a language neutral guide is fine too.
The desired behaviour is that if someone types into the GUI something like
`very nice;) DROP TABLE FOO;`
The database should treat it as a literal string and store it safely without dropping any tables. | You definitely want to use [PreparedStatement](https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html)s. They are convenient. Here is an [example](http://www.java2s.com/Code/Java/Database-SQL-JDBC/DemoPreparedStatementAddBatchMySQL.htm). | Use [PreparedStatement](https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html) instead of [Statement](https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html) | How should I sanitize database input in Java? | [
"",
"java",
"mysql",
"security",
"sql-injection",
""
] |
Usually not calling Dispose indicates a possible error or sloppy code and may lead to some hard to find bugs. Ideally I would like to spot if Disposed was not called during unit tests.
One of the methods we used was to put Debug.Assert in the Finalizer
```
#if DEBUG
~MyClass()
{
Debug.Assert(false, “MyClass.Dispose() was not called”);
}
#endif
```
And we found ourselves clicking through assert message boxes but it didn’t work well with continuous integration builds that would ignore the popups. | If you log this somehow instead of using a Debug.Assert, and used dependency injection to specify your logger implementation, then you could use mock testing to catch this. So,
your class may take a logger instance in its constructor, or provide a default one, and then behave like this:
```
public MyClass : IDisposable
{
IEventLogger _eventLogger;
public MyClass() : this(EventLogger.CreateDefaultInstance())
{
}
public MyClass(IEventLogger eventLogger)
{
_eventLogger = eventLogger;
}
// IDisposable stuff...
#if DEBUG
~MyClass()
{
_eventLogger.LogError("MyClass.Dispose() was not called");
}
#endif
}
``` | It is possible to write an fxCop rule to detect this issue.
Also, making sure that all uses of IDisposable are used inside a using{} block makes this much easier to deal with.
the rule I had checked for either manual calls to Dispose() or use of using{}
Manual calls to dispose are of course more difficult to detect in all situations, since there might be flow control or exceptions that may prevent the call from occurring. | How to make sure that Dispose method was called on IDisposable object and if possible to integrate it into continuous integration? | [
"",
"c#",
"unit-testing",
""
] |
This is a snippet from my `index.php` page, where I'm displaying a menu with three HTML links.
Selecting a menu item defines the page parameter, which the PHP templating logic then loads, populating into `<div id="main">`.
```
<div class="span-24" id="menu">
<table>
<tr>
<td><a href="index.php?page=races">Races</a></td>
<td><a href="index.php?page=runners">Runners</a></td>
<td><a href="index.php?page=searchRunners">Search</a></td>
</tr>
</table>
<br/>
</div>
<!-- main content -->
<div class="span-24" id="main">
<?php
$MYROOT=$_SERVER['DOCUMENT_ROOT'];
if(isset($_GET['page']))
{
$page=$_GET['page'];
@ require_once($MYROOT."/$page.php");
}
else
{
@ require_once($MYROOT."/races.php");
}
?>
</div>
```
This solution works fine, but I'm worried that as I add more pages and have more page parameters to track, this approach will become difficult to maintain with the various PHP `require()` / `require_once()` method calls.
I also have jQuery available and I was wondering what could be the benefits or drawbacks of just using a AJAX based query to render the HTML for `<div id="main">`.
I think using AJAX might be a better solution, since I'll have more flexibility in the page that I can call and which parameters I can pass within the AJAX call.
I know PHP and the AJAX can be used together, but if you were starting this type of project, how would you do it? | You don't want to do this. AJAX is nice and all but this would be misusing it. It would not only needlessly make the website inaccessible to people with Javascript disabled (which I'm sure you're aware of), it would also kill the navigational standard of the web on your website. How could someone send a link to a friend to check out the Races page, then? How can I go back and forth between pages? There's workarounds to this, but it is not worth it. You are better suited to just re-factor your PHP code so it is dynamic while safe in including what you want. | To expand on what Paolo said, Google and other search engines can't "crawl" any content loaded via javascript. That means only the static information on the page would get indexed, and your page ranking would be all but non-existent. | To use PHP templates or jQuery AJAX calls? | [
"",
"php",
"jquery",
"ajax",
""
] |
Is there any documentation on exactly how expensive it is:
```
if (x.IsInvokeRequired)
{
beginInvoke . . . .
}
```
* If you have a case where 90% of the time is on a background thread (and thus required) is it worth it?
* If you have a case where 90% of the time is on a UI thread (and thus not required) is it worth it?
Any metrics around this would be great. | ## Real Answer:
Use a profiler
## Fuzzy Answer:
I think you need to consider the relative costs of both functions vs. the absolute cost of InvokeRequired.
InvokeRequired for Control essentially compares the current ThreadId with the expected ThreadId. If you look in reflector the code is slightly more complex but in effect that's what it's doing. This is fairly cheap as it's just a few function calls and a comparison.
BeginInvoke involves taking several locks, adding delegates to an invoke queue and potentially a Marshal between threads. This code is much more expensive relative to the actual InvokeRequired call (likely an order of magnitude or 2). You would need a great deal more calls where InvokeRequired returns true before you would see any gain by just going straight to BeignInvoke. | No metrics, but a quick trip into Reflector tells us that the call is most likely not very expensive at all:
```
[SRDescription("ControlInvokeRequiredDescr"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)]
public bool InvokeRequired
{
get
{
using (new MultithreadSafeCallScope())
{
HandleRef ref2;
int num;
if (this.IsHandleCreated)
{
ref2 = new HandleRef(this, this.Handle);
}
else
{
Control wrapper = this.FindMarshalingControl();
if (!wrapper.IsHandleCreated)
{
return false;
}
ref2 = new HandleRef(wrapper, wrapper.Handle);
}
int windowThreadProcessId = SafeNativeMethods.GetWindowThreadProcessId(ref2, out num);
int currentThreadId = SafeNativeMethods.GetCurrentThreadId();
return (windowThreadProcessId != currentThreadId);
}
}
}
```
It's likely best to make the check regardless of the usage, as any performance gain from this sort of micro-optimization would be more than offset by the risk of an issue popping up. | How expensive is the IsInvokeRequired | [
"",
"c#",
"multithreading",
""
] |
Is there a reason why passing a reference to a `std::map` as const causes the [] operator to break? I get this compiler error (gcc 4.2) when I use const:
> error: no match for ‘operator[]’ in
> ‘map[name]’
Here's the function prototype:
```
void func(const char ch, std::string &str, const std::map<std::string, std::string> &map);
```
And, I should mention that there is no problem when I remove the `const` keyword in front of `std::map`.
If I've been instructed correctly, the [] operator will actually insert a new pair into the map if it doesn't find the key, which would of course explain why this happens, but I can't imagine that this would ever be acceptable behavior.
If there is a better method, like using *find* instead of [], I'd appreciate it. I can't seem to get find to work either though... I receive *const* mismatched iterator errors. | Yes you can't use `operator[]`. Use `find`, but note it returns `const_iterator` instead of `iterator`:
```
std::map<std::string, std::string>::const_iterator it;
it = map.find(name);
if(it != map.end()) {
std::string const& data = it->second;
// ...
}
```
It's like with pointers. You can't assign `int const*` to `int*`. Likewise, you can't assign `const_iterator` to `iterator`. | When you're using operator[], std::map looks for item with given key. If it does not find any, it creates it. Hence the problem with const.
Use find method and you'll be fine.
Can you please post code on how you're trying to use find() ?
The right way would be :
```
if( map.find(name) != map.end() )
{
//...
}
``` | C++ const std::map reference fails to compile | [
"",
"c++",
"find",
"std",
"operator-keyword",
"stdmap",
""
] |
A lot of C++ books and tutorials explain how to do this, but I haven't seen one that gives a convincing reason to choose to do this.
I understand very well why function pointers were necessary in C (e.g., when using some POSIX facilities). However, AFAIK you can't send them a member function because of the "this" parameter. But if you're already using classes and objects, why not just use an object oriented solution like functors?
Real world examples of where you had to use such function pointers would be appreciated.
Update: I appreciate everyone's answers. I have to say, though, that none of these examples really convinces me that this is a valid mechanism from a pure-OO perspective... | Functors are not a priori object-oriented (in C++, the term “functor” usually means a struct defining an `operator ()` with arbitrary arguments and return value that can be used as syntactical drop-in replacements to real functions or function pointers). However, their object-oriented problem has a lot of issues, first and foremost usability. It's just a whole lot of complicated boilerplate code. In order for a decent signalling framework as in most dialog frameworks, a whole lot of inheritance mess becomes necessary.
Instance-bound function pointers would be very beneficial here (.NET demonstrates this amply with delegates).
However, C++ member function pointers satisfy another need still. Imagine, for example, that you've got a lot of values in a list of which you want to execute one method, say its `print()`. A function pointer to `YourType::size` helps here because it lets you write such code:
```
std::for_each(lst.begin(), lst.end(), std::mem_fun(&YourType::print))
``` | In the past, member function pointers used to be useful in scenarios like this:
```
class Image {
// avoid duplicating the loop code
void each(void(Image::* callback)(Point)) {
for(int x = 0; x < w; x++)
for(int y = 0; y < h; y++)
callback(Point(x, y));
}
void applyGreyscale() { each(&Image::greyscalePixel); }
void greyscalePixel(Point p) {
Color c = pixels[p];
pixels[p] = Color::fromHsv(0, 0, (c.r() + c.g() + c.b()) / 3);
}
void applyInvert() { each(&Image::invertPixel); }
void invertPixel(Point p) {
Color c = pixels[p];
pixels[p] = Color::fromRgb(255 - c.r(), 255 - r.g(), 255 - r.b());
}
};
```
I've seen that used in a commercial painting app. (interestingly, it's one of the few C++ problems better solved with the preprocessor).
Today, however, the only use for member function pointers is inside the implementation of `boost::bind`. | Why would one use function pointers to member method in C++? | [
"",
"c++",
"function-pointers",
""
] |
I've been attempting to create a new process under the context of a specific user using the `CreateProcessAsUser` function of the Windows API, but seem to be running into a rather nasty security issue...
Before I explain any further, here's the code I'm currently using to start the new process (a console process - PowerShell to be specific, though it shouldn't matter).
```
private void StartProcess()
{
bool retValue;
// Create startup info for new console process.
var startupInfo = new STARTUPINFO();
startupInfo.cb = Marshal.SizeOf(startupInfo);
startupInfo.dwFlags = StartFlags.STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = _consoleVisible ? WindowShowStyle.Show : WindowShowStyle.Hide;
startupInfo.lpTitle = this.ConsoleTitle ?? "Console";
var procAttrs = new SECURITY_ATTRIBUTES();
var threadAttrs = new SECURITY_ATTRIBUTES();
procAttrs.nLength = Marshal.SizeOf(procAttrs);
threadAttrs.nLength = Marshal.SizeOf(threadAttrs);
// Log on user temporarily in order to start console process in its security context.
var hUserToken = IntPtr.Zero;
var hUserTokenDuplicate = IntPtr.Zero;
var pEnvironmentBlock = IntPtr.Zero;
var pNewEnvironmentBlock = IntPtr.Zero;
if (!WinApi.LogonUser("UserName", null, "Password",
LogonType.Interactive, LogonProvider.Default, out hUserToken))
throw new Win32Exception(Marshal.GetLastWin32Error(), "Error logging on user.");
var duplicateTokenAttrs = new SECURITY_ATTRIBUTES();
duplicateTokenAttrs.nLength = Marshal.SizeOf(duplicateTokenAttrs);
if (!WinApi.DuplicateTokenEx(hUserToken, 0, ref duplicateTokenAttrs,
SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary,
out hUserTokenDuplicate))
throw new Win32Exception(Marshal.GetLastWin32Error(), "Error duplicating user token.");
try
{
// Get block of environment vars for logged on user.
if (!WinApi.CreateEnvironmentBlock(out pEnvironmentBlock, hUserToken, false))
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Error getting block of environment variables for user.");
// Read block as array of strings, one per variable.
var envVars = ReadEnvironmentVariables(pEnvironmentBlock);
// Append custom environment variables to list.
foreach (var var in this.EnvironmentVariables)
envVars.Add(var.Key + "=" + var.Value);
// Recreate environment block from array of variables.
var newEnvironmentBlock = string.Join("\0", envVars.ToArray()) + "\0";
pNewEnvironmentBlock = Marshal.StringToHGlobalUni(newEnvironmentBlock);
// Start new console process.
retValue = WinApi.CreateProcessAsUser(hUserTokenDuplicate, null, this.CommandLine,
ref procAttrs, ref threadAttrs, false, CreationFlags.CREATE_NEW_CONSOLE |
CreationFlags.CREATE_SUSPENDED | CreationFlags.CREATE_UNICODE_ENVIRONMENT,
pNewEnvironmentBlock, null, ref startupInfo, out _processInfo);
if (!retValue) throw new Win32Exception(Marshal.GetLastWin32Error(),
"Unable to create new console process.");
}
catch
{
// Catch any exception thrown here so as to prevent any malicious program operating
// within the security context of the logged in user.
// Clean up.
if (hUserToken != IntPtr.Zero)
{
WinApi.CloseHandle(hUserToken);
hUserToken = IntPtr.Zero;
}
if (hUserTokenDuplicate != IntPtr.Zero)
{
WinApi.CloseHandle(hUserTokenDuplicate);
hUserTokenDuplicate = IntPtr.Zero;
}
if (pEnvironmentBlock != IntPtr.Zero)
{
WinApi.DestroyEnvironmentBlock(pEnvironmentBlock);
pEnvironmentBlock = IntPtr.Zero;
}
if (pNewEnvironmentBlock != IntPtr.Zero)
{
Marshal.FreeHGlobal(pNewEnvironmentBlock);
pNewEnvironmentBlock = IntPtr.Zero;
}
throw;
}
finally
{
// Clean up.
if (hUserToken != IntPtr.Zero)
WinApi.CloseHandle(hUserToken);
if (hUserTokenDuplicate != IntPtr.Zero)
WinApi.CloseHandle(hUserTokenDuplicate);
if (pEnvironmentBlock != IntPtr.Zero)
WinApi.DestroyEnvironmentBlock(pEnvironmentBlock);
if (pNewEnvironmentBlock != IntPtr.Zero)
Marshal.FreeHGlobal(pNewEnvironmentBlock);
}
_process = Process.GetProcessById(_processInfo.dwProcessId);
}
```
For the sake of the issue here, ignore the code dealing with the environment variables (I've tested that section independently and it seems to work.)
Now, the error I get is the following (thrown at the line following the call to `CreateProcessAsUSer`):
> "A required privilege is not held by the client" (error code 1314)
(The error message was discovered by removing the message parameter from the Win32Exception constructor. Admittedly, my error handling code here may not be the best, but that's a somewhat irrelevant matter. You're welcome to comment on it if you wish, however.) I'm really quite confused as to the cause of this vague error in this situation. MSDN documentation and various forum threads have only given me so much advice, and especially given that the causes for such errors appear to be widely varied, I have no idea which section of code I need to modify. Perhaps it is simply a single parameter I need to change, but I could be making the wrong/not enough WinAPI calls for all I know. What confuses me greatly is that the previous version of the code that uses the plain `CreateProcess` function (equivalent except for the user token parameter) worked perfectly fine. As I understand, it is only necessary to call the Logon user function to receive the appropriate token handle and then duplicate it so that it can be passed to `CreateProcessAsUser`.
Any suggestions for modifications to the code as well as explanations would be very welcome.
## Notes
I've been primarily referring to the MSDN docs (as well as [PInvoke.net](http://pinvoke.net) for the C# function/strut/enum declarations). The following pages in particular seem to have a lot of information in the Remarks sections, some of which may be important and eluding me:
* [CreateProcessAsUser function](http://msdn.microsoft.com/en-us/library/ms682429(VS.85).aspx)
* [LogonUser function](http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx)
* [DuplicateTokenEx function](http://msdn.microsoft.com/en-us/library/aa446617(VS.85).aspx)
# Edit
I've just tried out Mitch's suggestion, but unfortunately the old error has just been replaced by a new one: "The system cannot find the file specified." (error code 2)
The previous call to `CreateProcessAsUser` was replaced with the following:
```
retValue = WinApi.CreateProcessWithTokenW(hUserToken, LogonFlags.WithProfile, null,
this.CommandLine, CreationFlags.CREATE_NEW_CONSOLE |
CreationFlags.CREATE_SUSPENDED | CreationFlags.CREATE_UNICODE_ENVIRONMENT,
pNewEnvironmentBlock, null, ref startupInfo, out _processInfo);
```
Note that this code no longer uses the duplicate token but rather the original, as the MSDN docs appear to suggest.
And here's another attempt using `CreateProcessWithLogonW`. The error this time is "Logon failure: unknown user name or bad password" (error code 1326)
```
retValue = WinApi.CreateProcessWithLogonW("Alex", null, "password",
LogonFlags.WithProfile, null, this.CommandLine,
CreationFlags.CREATE_NEW_CONSOLE | CreationFlags.CREATE_SUSPENDED |
CreationFlags.CREATE_UNICODE_ENVIRONMENT, pNewEnvironmentBlock,
null, ref startupInfo, out _processInfo);
```
I've also tried specifying the username in UPN format ("Alex@Alex-PC") and passing the domain independently as the second argument, all to no avail (identical error). | Ahh... seems liker I've been caught out by one of the biggest gotchas in WinAPI interop programming. Also, Posting the code for my function declarations would have been a wise idea in this case.
Anyway, all that I needed to do was add an argument to the DllImport attribute of the function specifying `CharSet = CharSet.Unicode`. This did the trick for both the `CreateProcessWithLogonW` and `CreateProcessWithTokenW` functions. I guess it finally just hit me that the W suffix of the function names referred to Unicode and that I needed to explicitly specify this in C#! Here are the *correct* function declarations in case anyone is interested:
```
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CreateProcessWithLogonW(string principal, string authority,
string password, LogonFlags logonFlags, string appName, string cmdLine,
CreationFlags creationFlags, IntPtr environmentBlock, string currentDirectory,
ref STARTUPINFO startupInfo, out PROCESS_INFORMATION processInfo);
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CreateProcessWithTokenW(IntPtr hToken, LogonFlags dwLogonFlags,
string lpApplicationName, string lpCommandLine, CreationFlags dwCreationFlags,
IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
``` | From [here](http://msdn.microsoft.com/en-us/library/ms682429(VS.85).aspx):
> Typically, the process that calls the
> CreateProcessAsUser function must have
> the SE\_ASSIGNPRIMARYTOKEN\_NAME and
> SE\_INCREASE\_QUOTA\_NAME privileges. If
> this function fails with
> ERROR\_PRIVILEGE\_NOT\_HELD (1314), use
> the CreateProcessWithLogonW function
> instead. CreateProcessWithLogonW
> requires no special privileges, but
> the specified user account must be
> allowed to log on interactively.
> Generally, it is best to use
> CreateProcessWithLogonW to create a
> process with alternate credentials.
See this blog post [How to call CreateProcessWithLogonW & CreateProcessAsUser in .NET](http://blogs.msdn.com/alejacma/archive/2007/12/20/how-to-call-createprocesswithlogonw-createprocessasuser-in-net.aspx) | Calling CreateProcessAsUser from C# | [
"",
"c#",
"winapi",
"process",
"privileges",
"createprocessasuser",
""
] |
how is it possible to know whether an object implements an indexer?, I need to share a logic for a DataRow and a IDataReader, but they don't share any interface.
I tried also with generics but don't know what restriction should I put on the where clause.
```
public class Indexer {
// myObject should be a DataRow or a IDataReader
private object myObject;
public object MyObject {
get { return myObject; }
set { myObject = value; }
}
// won't compile, myObject has no indexer
public object this[int index] {
get { return myObject[index]; }
set { myObject[index] = value; }
}
public Indexer(object myObject) {
this.myObject = myObject;
}
}
public class Caller {
void Call() {
DataRow row = null;
IDataReader reader = null;
var ind1 = new Indexer(row);
var ind2 = new Indexer(reader);
var val1 = ind1[0];
var val2 = ind1[0];
}
}
``` | You'd need to declare an interface with an indexer property, use that interface as the constraint, and the type argument class would need to implement that interface in order to satisfy the constraint.
As you don't control the classes you want to use, that wouldn't work.
An alternative is to make the `Indexer` class take the get/set operations as separate parameters:
```
public class Indexer {
private Func<int, object> getter;
private Action<int, object> setter;
public object this[int index]
{
get { return getter(index); }
set { setter(index, value); }
}
public Indexer(Func<int, object> g, Action<int, object> s)
{
getter = g;
setter = s;
}
}
public static class IndexerExtensions
{
public static Indexer ToIndexer(this DataRow row)
{
return new Indexer(n => row[n], (n, v) => row[n] = v);
}
public static Indexer ToIndexer(this IDataReader row)
{
return new Indexer(n => row[n], (n, v) => row[n] = v);
}
}
```
You could then do this:
```
DataRow row = null;
IDataReader reader = null;
var ind1 = row.ToIndexer();
var ind2 = reader.ToIndexer();
var val1 = ind1[0];
var val2 = ind1[0];
``` | You could make your Indexer an abstract base class, with two subclasses, one for DataRow, and one for IDataReader.
To make it easier to use, 2 factory methods could exist, such as:
```` ```
var ind1 = Indexer.CreateFromDataRow(row);
var ind2 = Indexer.CreateFromIDataReader(reader);
``` ````
They could create a specific base class for that type, with it's own logic for handling the indexing.
This avoids the overhead of checking types constantly for every get/set call (at the cost of a single virtual property instead of a standard property). | Question about indexers and/or generics | [
"",
"c#",
"generics",
"indexer",
""
] |
The C#/.NET application I am working on is suffering from a slow memory leak. I have used CDB with SOS to try to determine what is happening but the data does not seem to make any sense so I was hoping one of you may have experienced this before.
The application is running on the 64 bit framework. It is continuously calculating and serialising data to a remote host and is hitting the Large Object Heap (LOH) a fair bit. However, most of the LOH objects I expect to be transient: once the calculation is complete and has been sent to the remote host, the memory should be freed. What I am seeing, however, is a large number of (live) object arrays interleaved with free blocks of memory, e.g., taking a random segment from the LOH:
```
0:000> !DumpHeap 000000005b5b1000 000000006351da10
Address MT Size
...
000000005d4f92e0 0000064280c7c970 16147872
000000005e45f880 00000000001661d0 1901752 Free
000000005e62fd38 00000642788d8ba8 1056 <--
000000005e630158 00000000001661d0 5988848 Free
000000005ebe6348 00000642788d8ba8 1056
000000005ebe6768 00000000001661d0 6481336 Free
000000005f214d20 00000642788d8ba8 1056
000000005f215140 00000000001661d0 7346016 Free
000000005f9168a0 00000642788d8ba8 1056
000000005f916cc0 00000000001661d0 7611648 Free
00000000600591c0 00000642788d8ba8 1056
00000000600595e0 00000000001661d0 264808 Free
...
```
Obviously I would expect this to be the case if my application were creating long-lived, large objects during each calculation. (It does do this and I accept there will be a degree of LOH fragmentation but that is not the problem here.) The problem is the very small (1056 byte) object arrays you can see in the above dump which I cannot see in code being created and which are remaining rooted somehow.
Also note that CDB is not reporting the type when the heap segment is dumped: I am not sure if this is related or not. If I dump the marked (<--) object, CDB/SOS reports it fine:
```
0:015> !DumpObj 000000005e62fd38
Name: System.Object[]
MethodTable: 00000642788d8ba8
EEClass: 00000642789d7660
Size: 1056(0x420) bytes
Array: Rank 1, Number of elements 128, Type CLASS
Element Type: System.Object
Fields:
None
```
The elements of the object array are all strings and the strings are recognisable as from our application code.
Also, I am unable to find their GC roots as the !GCRoot command hangs and never comes back (I have even tried leaving it overnight).
So, I would very much appreciate it if anyone could shed any light as to why these small (<85k) object arrays are ending up on the LOH: what situations will .NET put a small object array in there? Also, does anyone happen to know of an alternative way of ascertaining the roots of these objects?
---
Update 1
Another theory I came up with late yesterday is that these object arrays started out large but have been shrunk leaving the blocks of free memory that are evident in the memory dumps. What makes me suspicious is that the object arrays always appear to be 1056 bytes long (128 elements), 128 \* 8 for the references and 32 bytes of overhead.
The idea is that perhaps some unsafe code in a library or in the CLR is corrupting the number of elements field in the array header. Bit of a long shot I know...
---
Update 2
Thanks to Brian Rasmussen (see accepted answer) the problem has been identified as fragmentation of the LOH caused by the string intern table! I wrote a quick test application to confirm this:
```
static void Main()
{
const int ITERATIONS = 100000;
for (int index = 0; index < ITERATIONS; ++index)
{
string str = "NonInterned" + index;
Console.Out.WriteLine(str);
}
Console.Out.WriteLine("Continue.");
Console.In.ReadLine();
for (int index = 0; index < ITERATIONS; ++index)
{
string str = string.Intern("Interned" + index);
Console.Out.WriteLine(str);
}
Console.Out.WriteLine("Continue?");
Console.In.ReadLine();
}
```
The application first creates and dereferences unique strings in a loop. This is just to prove that the memory does not leak in this scenario. Obviously it should not and it does not.
In the second loop, unique strings are created and interned. This action roots them in the intern table. What I did not realise is how the intern table is represented. It appears it consists of a set of pages -- object arrays of 128 string elements -- that are created in the LOH. This is more evident in CDB/SOS:
```
0:000> .loadby sos mscorwks
0:000> !EEHeap -gc
Number of GC Heaps: 1
generation 0 starts at 0x00f7a9b0
generation 1 starts at 0x00e79c3c
generation 2 starts at 0x00b21000
ephemeral segment allocation context: none
segment begin allocated size
00b20000 00b21000 010029bc 0x004e19bc(5118396)
Large object heap starts at 0x01b21000
segment begin allocated size
01b20000 01b21000 01b8ade0 0x00069de0(433632)
Total Size 0x54b79c(5552028)
------------------------------
GC Heap Size 0x54b79c(5552028)
```
Taking a dump of the LOH segment reveals the pattern I saw in the leaking application:
```
0:000> !DumpHeap 01b21000 01b8ade0
...
01b8a120 793040bc 528
01b8a330 00175e88 16 Free
01b8a340 793040bc 528
01b8a550 00175e88 16 Free
01b8a560 793040bc 528
01b8a770 00175e88 16 Free
01b8a780 793040bc 528
01b8a990 00175e88 16 Free
01b8a9a0 793040bc 528
01b8abb0 00175e88 16 Free
01b8abc0 793040bc 528
01b8add0 00175e88 16 Free total 1568 objects
Statistics:
MT Count TotalSize Class Name
00175e88 784 12544 Free
793040bc 784 421088 System.Object[]
Total 1568 objects
```
Note that the object array size is 528 (rather than 1056) because my workstation is 32 bit and the application server is 64 bit. The object arrays are still 128 elements long.
So the moral to this story is to be very careful interning. If the string you are interning is not known to be a member of a finite set then your application will leak due to fragmentation of the LOH, at least in version 2 of the CLR.
In our application's case, there is general code in the deserialisation code path that interns entity identifiers during unmarshalling: I now strongly suspect this is the culprit. However, the developer's intentions were obviously good as they wanted to make sure that if the same entity is deserialised multiple times then only one instance of the identifier string will be maintained in memory. | The CLR uses the LOH to preallocate a few objects (such as [the array used for interned strings](https://stackoverflow.com/questions/372547/where-do-java-and-net-string-literals-reside/372559#372559)). Some of these are less than 85000 bytes and thus would not normally be allocated on the LOH.
It is an implementation detail, but I assume the reason for this is to avoid unnecessary garbage collection of instances that are supposed to survive as long as the process it self.
Also due to a somewhat esoteric optimization, any `double[]` of 1000 or more elements is also allocated on the LOH. | The .NET Framework 4.5.1, has the ability to explicitly compact the large object heap (LOH) during garbage collection.
```
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
```
See more info in [GCSettings.LargeObjectHeapCompactionMode](http://msdn.microsoft.com/en-us/library/system.runtime.gcsettings.largeobjectheapcompactionmode(v=vs.110).aspx) | Large Object Heap Fragmentation | [
"",
"c#",
".net",
"memory-management",
"memory-leaks",
"windbg",
""
] |
Again a regex question.
What's more efficient? Cascading a lot of Regex.Replace with each one a specific pattern to search for OR only one Regex.Replace with an or'ed pattern (pattern1|pattern2|...)?
Thanks in advance,
Fabian | It depends on how big your text is and how many matches you expect. If at all possible, put a text literal or anchor (e.g. ^) at the front of the Regex. The .NET Regex engine will optimize this so that it searches for that text using a fast Boyer-Moore algorithm (which can skip characters) rather than a standard IndexOf that looks at each character. In the case that you have several patterns with literal text at the front, there is an optimization to create a set of possible start characters. All others are ignored quickly.
In general, you might want to consider reading [Mastering Regular Expressions](https://rads.stackoverflow.com/amzn/click/com/0596528124) which highlights general optimizations to get an idea for better performance (especially chapter 6).
I'd say you might get faster perf if you put everything in one Regex, but put the most likely option first, followed by the second most likely, etc. The number one thing to watch out for is backtracking. If you do something like
```
".*"
```
to match a quoted string, realize that once it finds the first " then it will always go to the end of the line by default and then start backing up until it finds another ".
The [Mastering Regular Expressions](https://rads.stackoverflow.com/amzn/click/com/0596528124) book heavily goes into how to avoid this. | My answer sucks but: it depends. How many do you have? Will the few milliseconds you save really make a difference? Which solution is the most readable, the easiest to maintain, the most scalable?
Try both methods with your specific requirements at hand and you will see. You could be surprised. | Multiple Regex.Replace or or'ed pattern? | [
"",
"c#",
"regex",
""
] |
I wonder if I could read or write shared int value without locking on mips cpu (especially Amazon or Danube). What I mean is if such a read or write are atomic (other thread can't interrupt them). To be clear - I don't want to prevent the race between threads, but I care if int value itself is not corrupted.
Assuming that the compiler aligns all ints at the boundaries of cpu word, it should be possible. I use gcc (g++). Tests also shows that it seems work correctly. But maybe someone knows it for sure? | Use gcc's builtin atomic operations and you'll get warnings if they're not supported:
<http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html>
It looks like combinations of addition/subtraction and testing (at least) are possible on the hardware:
<http://rswiki.csie.org/lxr/http/source/include/asm-mips/atomic.h> | Depends on the operation. Having stared at enough disassembled programs in MIPS, I know that only some operations are atomic.
assignment of a new value could be 1 op or more, you'd have to look at the assembly.
eg:
```
x = 0; // move $a0, $0
x = 0x50000; // lui $a0, 0x0005
x = 0x50234; // lui $a0, 0x0005
// ori $a0, 0x0234
```
MIPS assembley [reference](http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html) or [here](http://en.wikipedia.org/wiki/MIPS_architecture#Integer)
see [here](https://svn.openwrt.org/openwrt/trunk/package/uboot-ifxmips/patches/100-ifx.patch) to see danube and amazon are MIPS32, which my example covers, and therefore not all 32bit integer immediate can be written atomically.
see [R10000](http://en.wikipedia.org/wiki/R10000) in above posting is MIPS64. Since a 32bit value would be half the register size, it could be an atomic load/write. | Are C++ int operations atomic on the mips architecture | [
"",
"c++",
"multithreading",
"mips",
"processor",
"cpu-architecture",
""
] |
Oracle pads values in char columns so if I insert "a" in a CHAR(2) column then I cannot get that record by comparing that column to "a", I should get it by comparing it to "a ". Right?
To solve this problem the Oracle jdbc driver has the property fixedString but I cannot make it work. (look for *fixedString* [here](https://docs.oracle.com/database/121/JAJDB/oracle/jdbc/OracleConnection.html#CONNECTION_PROPERTY_FIXED_STRING))
I'm using ojdbc14.jar driver for Oracle 10gR2 and accessing an Oracle 10gR2 database.
This is my code:
```
try {
Properties props = new Properties();
props.put("user", "****");
props.put("password", "****");
props.put("fixedString", true);
Class.forName("oracle.jdbc.driver.OracleDriver");
String jdbcUrl = "jdbc:oracle:thin:@<host>:<port>:<sid>";
Connection connection = DriverManager.getConnection(jdbcUrl, props);
PreparedStatement ps = connection.prepareStatement(
"SELECT * FROM MY_TABLE WHERE MY_TABLE_ID = ?");
ps.setObject(1, "abc"); // (*)
// MY_TABLE_ID is CHAR(15)
ResultSet rs = ps.executeQuery();
while (rs.next())
{
System.out.print("data: ");
System.out.println(rs.getString("MY_TABLE_ID"));
}
rs.close();
ps.close();
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
```
The above code executes fine (no exceptions thrown) but the ResultSet is empty after executeQuery().
If I change the line (\*) for
```
ps.setObject(1, "abc ");
```
Then I get the column I wanted. So it seems the driver is ignoring the fixedString option.
I've also tried changing the line (\*) for
```
ps.setObject(1, "abc", java.sql.Types.CHAR);
```
But the ResultSet I get is empty again. **What am I missing?**
Thanks in advance | Try using it as
```
props.put("fixedString", "true");
```
Oracle documentation says fixedString as String (containing boolean value) | You should only use CHAR for strings that will be the same length for every entry in the database. Use VARCHAR for variable length strings. | How to use Oracle jdbc driver fixedString property? | [
"",
"java",
"oracle",
"jdbc",
""
] |
How can I get the last value of an ArrayList? | The following is part of the [`List`](http://java.sun.com/javase/6/docs/api/java/util/List.html) interface (which ArrayList implements):
```
E e = list.get(list.size() - 1);
```
`E` is the element type. If the list is empty, `get` throws an [`IndexOutOfBoundsException`](http://java.sun.com/javase/6/docs/api/java/lang/IndexOutOfBoundsException.html). You can find the whole API documentation [here](http://java.sun.com/javase/6/docs/api/). | There isn't an elegant way in vanilla Java prior to Java 21.
# Google Guava
The [Google Guava](https://github.com/google/guava) library is great - check out their [`Iterables.getLast()`](https://guava.dev/releases/snapshot/api/docs/com/google/common/collect/Iterables.html#getLast(java.lang.Iterable)) method. This method will throw a [`NoSuchElementException`](http://docs.oracle.com/javase/8/docs/api/java/util/NoSuchElementException.html?is-external=true) if the list is empty, as opposed to an [`IndexOutOfBoundsException`](http://docs.oracle.com/javase/8/docs/api/java/lang/IndexOutOfBoundsException.html), as with the typical `size()-1` approach - I find a `NoSuchElementException` much nicer, or the ability to specify a default:
```
lastElement = Iterables.getLast(iterableList);
```
You can also provide a default value if the list is empty, instead of an exception:
```
lastElement = Iterables.getLast(iterableList, null);
```
or, if you're using `Option`s:
```
lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
``` | How to get the last value of an ArrayList | [
"",
"java",
"arraylist",
""
] |
How to get upper paths from a single path?
So say you have a path like:
```
'C:\a\b\c\d\'
```
How do I get to `'C:\a\b'` or `'C:\a\b\c'`
Is there a pythonic way to do this? | See [`os.path`](http://docs.python.org/library/os.path.html)
```
from os import path
path.dirname("C:\\a\\b\\c\\d\\")
``` | Theres basic stuff like [os.path](http://docs.python.org/library/os.path.html) methods.
If you want a list of the full path names of each successive parent in the directory tree, heres a one liner:
```
from os.path import dirname
def f1(n): return [n] if n == dirname(n) else [n] + f1(dirname(n))
print f1("/a/b/c/d/e/f/g")
``` | How to get upper paths from a single path? | [
"",
"python",
"directory",
""
] |
I'm frequently frustrated by the amount of logging I have to include in my code and it leads me to wonder if there's a better way of doing things.
I don't know if this has been done or if someone has come up with a better idea but I was wondering is there a way anyone knows of to "inject" a logger into an application such that it passively monitors the thread and quietly logs processes as they occur without having to do things like:
```
public void MyProcess(int a, string b, object c)
{
log(
String.Format(
"Entering process MyProcess with arguments: [a] = [{0}]; [b] = [{1}]; [c] = [{2}]",
a.ToString(),
b,
c.ToString()
);
try
{
int d = DoStuff(a)
log(
String.Format(
"DoStuff({0}) returned value {1}",
a.ToString(),
d.ToString()
)
);
}
catch (Exception ex)
{
log(
String.Format("An exception occurred during process DoStuff({0})\nException:\n{1}",
a.ToString(),
ex.ToString())
)
}
}
```
What would be great is if I could say to my logger:
```
Monitor(MyClass.MyMethod)
```
It would then monitor everything that goes on inside of that method including passed in arguments along with method calls and values passed into those methods, exceptions that occur etc.
Has anyone implemented something like this in the past? Could it even *be* implemented? Is logging in this fashion just a pipe dream?
I'd love to design something that would do this, but I just don't even know where I'd begin. Of course, I don't want to reinvent the wheel either, if it's already been done, it would be great if someone could point me in the right direction.
Any suggestions would be gratefully received...
**Edit:** I thought I'd comment on an answer which queried as to the level of detail required in the log. It is frequently required that configurable levels of logging be provided such that if the configuration specifies detailed logging then everything is logged, whereas if critical logging is configured then only certain information is logged along with exceptions. If fatal logging is configured then only information which causes the application to die would be logged. Would something like this be configurable or would AOP require 3 or 4 different builds depending on the number of logging levels?
I frequently use 4 levels: Fatal, Critical, Information, Detailed | You can use [PostSharp](http://postsharp.org) to log "around" the method. This is exactly the kind of thing AOP is good at. You might want to start with [Log4PostSharp](http://code.google.com/p/postsharp-user-plugins/wiki/Log4PostSharp) - a plugin specifically for logging. | This is the classic example from Aspect Oriented Programming. See PostSharp for a very good CLR-based library. | Is passive logging possible in .NET? | [
"",
"c#",
".net",
"asp.net",
"vb.net",
".net-3.5",
""
] |
Is it possible to get two separate programs to communicate on the same computer (one-way only) over UDP through localhost/127... by sharing the same port #?
We're working on a student project in which we need to send UDP packets containing some telemetry between two computers. The program that generates these packets is proprietary, but I'm working on the receiver program myself with C# using *System.Net.Sockets.UdpClient* and *System.Net.IPEndPoint*.
This works fine during our group's meetings when we have multiple computers connected on which we can run the two programs separately. But it's not very useful when I'm home and trying to expand on the telemetry processing program as I only have one computer (I need a feed for testing the processing program). I can not install the program on any of the school's computers either.
When I try to run both programs on my computer at the same time (starting my program last) I get a SocketException saying that only a single use of each port is *normally* allowed. Which leads me to believe there must be some way to share the port (although it makes sense that only a single program can use port on a computer at any one time, I have no trouble running multiple internet browsers at the same time (and I suppose they use port 80 for http)).
REEDIT of the EDIT:
sipwiz was right, and thanks to Kalmi for the pointer to UdpClient.Client.Bind().
At the time, though, we are considering using another program that generates similar packets, and with which we are able to share port with on the same computer using my first (although naive) approach with the UDP client binding in the ctor.
Sorry for having to unmark your answer, sysrqb. | I did not expect this to be possible, but.. well.. **sipwiz** was right.
It can be done very easily. **(Please vote sipwiz's answer up!)**
```
IPEndPoint localpt = new IPEndPoint(IPAddress.Any, 6000);
//Failed try
try
{
var u = new UdpClient(5000);
u.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
UdpClient u2 = new UdpClient(5000);//KABOOM
u2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
}
catch (Exception)
{
Console.WriteLine("ERROR! You must call Bind only after setting SocketOptionName.ReuseAddress. \n And you must not pass any parameter to UdpClient's constructor or it will call Bind.");
}
//This is how you do it (kudos to sipwiz)
UdpClient udpServer = new UdpClient(localpt); //This is what the proprietary(see question) sender would do (nothing special)
//!!! The following 3 lines is what the poster needs...(and the definition of localpt (of course))
UdpClient udpServer2 = new UdpClient();
udpServer2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer2.Client.Bind(localpt);
``` | You can bind to a port multiple times using the ReuseAddress socket option.
```
UdpClient udpClient = new UdpClient();
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
```
You'll need to set the same option on the UDP server socket as well. | Sending and receiving UDP packets between two programs on the same computer | [
"",
"c#",
"udp",
"localhost",
"port",
""
] |
I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game? | If all you want is a GUI, wxPython should do the trick.
If you're looking to add sound, controller input, and take it beyond a simple card game, then you may want to use pygame. | I haven't used wxPython, but Pygame by itself is rather low-level. It allows you to catch key presses, mouse events and draw stuff on the screen, but doesn't offer any pre-made GUI controls. If you use Pygame, you will either have to write your own GUI classes or use existing GUI extensions for Pygame, like [Phil's Pygame Utilities](http://www.imitationpickles.org/pgu/wiki/index). | wxPython or pygame for a simple card game? | [
"",
"python",
"wxpython",
"pygame",
"playing-cards",
""
] |
I might be nitpicking, but is it better to do this:
```
if ($loggedin) {
// normal process
}
else {
header('Location: login.php');
}
```
Or this:
```
if (!$loggedin) {
header('Location: login.php');
exit();
}
// normal process
```
Or does it just not matter? | I prefer the 2nd one because that way "normal process" is not already 1 indentation level deep because of a simple check. I think PHP probably optimizes this away so that performance is irrelevant, so at that point it's a matter of readability and the 2nd one makes more sense to me ("Not logged in, redirect, exit") over wrapping all your logic in one huge IF. | I prefer the second style, since "//normal process" is likely a long piece of code, so the last } (from the else branch) might be a bit confusing. | Best way to run a PHP script conditionally on user login | [
"",
"php",
"coding-style",
""
] |
Why does `IAsyncResult` require I keep a reference to the Delegate that `BeginInvoked` it?
I would like to be able to write something like:
```
new GenericDelegate(DoSomething).BeginInvoke(DoSomethingComplete);
void DoSomethingComplete(IAsyncResult ar)
{
ar.EndInvoke();
}
``` | You don't need to keep your own reference to a delegate when doing a normal1 delegate `BeginInvoke`; you can cast the `IAsyncResult` to an `AsyncResult` and retrieve the delegate from the `AsyncDelegate` property. And before anybody says "that's a dirty hack", [it's documented as being valid at MSDN](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.asyncresult.aspx).
> The AsyncResult class is used in conjunction with asynchronous method calls made using delegates. The IAsyncResult returned from the delegate's BeginInvoke method can be cast to an AsyncResult. The AsyncResult has the AsyncDelegate property that holds the delegate object on which the asynchronous call was invoked.
So you could write:
```
new GenericDelegate(DoSomething).BeginInvoke(DoSomethingComplete);
void DoSomethingComplete(IAsyncResult ar)
{
((GenericDelegate)((AsyncResult)ar).AsyncDelegate)).EndInvoke();
}
```
Note that you do still have to know the *type* of the original delegate (or at least, I haven't found a way around this limitation; then again I haven't tried).
---
1 By "normal" here I mean a `BeginInvoke` on a delegate instance, using the compiler-generated method. This technique of casting to `AsyncResult` is not guaranteed to work when using pre-defined methods, i.e. when using a class which declares its own `BeginX/EndX` methods. This is because the class may be doing something more clever internally such as blocking on IO completion ports, and may therefore use a different type of `IAsyncResult`. However, in the scenario as posited, it will work just fine. | I find the whole Begin/End pattern unnecessarily complex - so I [had a look at wrapping it up](http://marcgravell.blogspot.com/2009/02/async-without-pain.html) (very comparable to what F# uses). Result: no more need to keep the delegate (etc). | IAsyncResult reference | [
"",
"c#",
""
] |
I have a DIV with a script as shown below
```
<div style="text-align:center">
<script type='text/javascript' language='JavaScript' src='http://xslt.alexa.com/site_stats/js/t/a?url=www.mysite.com'></script>
</div>
```
What I want is that the users should not be able to see this div on the site, but the script should be executed as in the normal way. Please suggest! | I am not sure what it is you are including with that Javascript call, but if you want to hide the contents of this DIV just add this to the style declaration: `display: none;`
Check out the CSS [display](http://www.w3schools.com/css/pr_class_display.asp) documentation.
**EDIT**: The SCRIPT inside the DIV tag will still get loaded, which I believe is the desired effect. | Just change your style to
```
<div style="text-align:center; display: none;">
<script type='text/javascript' language='JavaScript' src='http://xslt.alexa.com/site_stats/js/t/a?url=www.mysite.com'></script>
</div>
``` | Hiding the contents of DIV | [
"",
"javascript",
"css",
""
] |
We have an Progress OpenEdge (<http://en.wikipedia.org/wiki/Progress_4GL>) develop team in the company I work for.
I'm the only c# developer there and really like it. So now the manager asks me to learn programming in OpenEdge. He doesn't want me to become a good OpenEdge programmer but he wants the team members to understand both worlds. He hopes the team will benefit from this.
I'm not unwilling to learn but I want to become a better developer and there are so many more aspects of .Net I like to discover.
So are there there any good point about Progress OpenEdge I would profit from or should I stay away from it. | 1. OpenEdge is a powerful framework for building CRUD applications; but it is a niche skill with no SAP-like salary premium for possessing it; conversely decent OpenEdge developers are hard to get hold of for bog standard rates - it would not be unknown for a manager to recruit an OpenEdge developer by the backdoor.
2. The core ABL (OpenEdge language) is different enough a language from the mainstream to be interesting for an inquisitive programmer and for your bosses arguments for everyone to understand where the others are coming from to make sense.
So, bearing those points in mind:
It's worth learning the basics to enrich your understanding of your core competencies, along the lines of "What should they of England know, who only England know?". You may also find the ease of data access eye-opening.
It is not worth spending too much time distracted from developing your expertise in a framework which is infinitely more widely used. | If your manager wants you to learn OpenEdge, then he has a reason for it. One reason could be that you will be taking on some of the development, perhaps providing cover when others are off. The other reason could be, as he says, that he want the team to understand both worlds.
What you need to find out is if the Progress people are going to be looking at .NET as well. If not, you know which of these reasons he has in mind. | Should I learn Openedge as a C# programmer | [
"",
"c#",
".net",
"openedge",
""
] |
I want to access `availJobs` in `jobs.scan` object but I couldn't. It is not defined in `jobs.attack`. What can I do to access the part of `jobs.scan` in other objects?
```
var jobs = new Array();
jobs.scan = function() {
var availJobs = new Array();
var jobContents = dom.get("app8743457343_content");
var boldthreads = jobContents.getElementsByTagName('b');
for(var i = 0; i < boldthreads.length; i++) {
if(boldthreads[i].style.color == 'silver') {
availJobs.push(boldthreads[i].textContent);
}
}
return availJobs;
}
jobs.attack = function() {
jobs.scan();
alert(jobs.availJobs[0]);
}
jobs.attack();
```
`availJobs[0]` in `jobs.attack` doesn't work. It's `undefined`. How can I set the `availJobs` as public and can be accessed in other objects?
Thanks for all the help!!
Here's the code that I put:
```
var jobs = {
availJobs: new Array(),
scan: function() {
var jobContents = dom.get("app8743457343_content");
var boldthreads = jobContents.getElementsByTagName('b');
for(var i = 0; i < boldthreads.length; i++) {
if(boldthreads[i].style.color == 'silver') {
this.availJobs.push(boldthreads[i].textContent);
}
}
},
attack: function() {
this.scan();
alert(this.availJobs[0]);
},
};
jobs.attack();
```
This code is definitely more elegant don't you think? I used this and it worked! | `{}` is used to initialize an object and Array to initialize an array.
```
var jobs = {
availJobs : new Array()
}
jobs.scan = function() {
var jobContents = dom.get("app8743457343_content");
var boldthreads = jobContents.getElementsByTagName('b');
for(var i = 0; i < boldthreads.length; i++) {
if(boldthreads[i].style.color == 'silver') {
availJobs.push(boldthreads[i].textContent);
}
}
return availJobs;
}
```
In a `{}` declaration, you can put add multiple members to your object if you separe them with a comma `,` :
```
var jobs = {
availJobs : new Array(),
anotherMember : null,
anotherArray : new Array(),
aFunction = function() {...}
}
``` | I may be wrong here, but I'm pretty sure you need to declare availJobs outside of the function itself, IE: `jobs.availJobs = new Array();` | How can I access a data from another object in JavaScript? | [
"",
"javascript",
""
] |
If I have the following function:
```
def intercept(func):
# do something here
@intercept(arg1=20)
def whatever(arg1,arg2):
# do something here
```
I would like for intercept to fire up only when **arg1** is 20. I would like to be able to pass named parameters to the function. How could I accomplish this?
Here's a little code sample :
```
def intercept(func):
def intercepting_func(*args,**kargs):
print "whatever"
return func(*args,**kargs)
return intercepting_func
@intercept(a="g")
def test(a,b):
print "test with %s %s" %(a,b)
test("g","d")
```
**This throws the following exception TypeError: intercept() got an unexpected keyword argument 'a'** | ```
from functools import wraps
def intercept(target,**trigger):
def decorator(func):
names = getattr(func,'_names',None)
if names is None:
code = func.func_code
names = code.co_varnames[:code.co_argcount]
@wraps(func)
def decorated(*args,**kwargs):
all_args = kwargs.copy()
for n,v in zip(names,args):
all_args[n] = v
for k,v in trigger.iteritems():
if k in all_args and all_args[k] != v:
break
else:
return target(all_args)
return func(*args,**kwargs)
decorated._names = names
return decorated
return decorator
```
Example:
```
def interceptor1(kwargs):
print 'Intercepted by #1!'
def interceptor2(kwargs):
print 'Intercepted by #2!'
def interceptor3(kwargs):
print 'Intercepted by #3!'
@intercept(interceptor1,arg1=20,arg2=5) # if arg1 == 20 and arg2 == 5
@intercept(interceptor2,arg1=20) # elif arg1 == 20
@intercept(interceptor3,arg2=5) # elif arg2 == 5
def foo(arg1,arg2):
return arg1+arg2
>>> foo(3,4)
7
>>> foo(20,4)
Intercepted by #2!
>>> foo(3,5)
Intercepted by #3!
>>> foo(20,5)
Intercepted by #1!
>>>
```
`functools.wraps` does what the "simple decorator" on the wiki does; Updates `__doc__`, `__name__` and other attribute of the decorator. | Remember that
```
@foo
def bar():
pass
```
is equivalent to:
```
def bar():
pass
bar = foo(bar)
```
so if you do:
```
@foo(x=3)
def bar():
pass
```
that's equivalent to:
```
def bar():
pass
bar = foo(x=3)(bar)
```
so your decorator needs to look something like this:
```
def foo(x=1):
def wrap(f):
def f_foo(*args, **kw):
# do something to f
return f(*args, **kw)
return f_foo
return wrap
```
In other words, `def wrap(f)` is really the decorator, and `foo(x=3)` is a function call that returns a decorator. | How can I use named arguments in a decorator? | [
"",
"python",
"language-features",
"decorator",
""
] |
What is the best way to recursively copy a folder's content into another folder using C# and ASP.NET? | Well you can try this
```
DirectoryInfo sourcedinfo = new DirectoryInfo(@"E:\source");
DirectoryInfo destinfo = new DirectoryInfo(@"E:\destination");
copy.CopyAll(sourcedinfo, destinfo);
```
and this is the method that do all the work:
```
public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
try
{
//check if the target directory exists
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
//copy all the files into the new directory
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
//copy all the sub directories using recursion
foreach (DirectoryInfo diSourceDir in source.GetDirectories())
{
DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name);
CopyAll(diSourceDir, nextTargetDir);
}
//success here
}
catch (IOException ie)
{
//handle it here
}
}
```
I hope this will help :) | Just use `Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory` in `Microsoft.VisualBasic.dll` assembly.
Add a reference to `Microsoft.VisualBasic`
```
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source, destination);
``` | What is the best way to recursively copy contents in C#? | [
"",
"c#",
"asp.net",
"recursion",
""
] |
We are experiencing random intermittent slow-downs in our ASP.NET application. Most pages take between 100-500ms to render (depending on which modules are used on the page). Occasionally however - perhaps 1 in 100 requests, these figures are more like 5000-10000ms. This is not a database related issue - I have checked for slow queries, and is not related to the complexity of the page - e.g. a page which takes 100ms is just as likely to take 10000ms when it slows down. I don't think the app-pool is recycling either - would normally see this in task manager. Could it possibly be GC? Any ideas? The w3wp application usually uses a steady 800MB-1GB of memory at all times.
Thanks
Marcus | The best thing I can tell you to do is to attach a profiler (search this site for a good .NET profiler, I personally use [ANTS](http://www.red-gate.com/Products/ants_profiler/index.htm)) to identify bottlenecks. Without good profile data all of our suggestions here will simply be speculation. | Does the application use the Cache at all for maintaining a large piece of static data? Even if the app-pool is not recycling, it's possible that some large objects in cache are being expired and then the next hit that requires that Cache has to refill it. | ASP.NET random slow downs | [
"",
"c#",
"asp.net",
"iis",
""
] |
How would I combine the following two queries to produce a combination of the two?
```
SELECT *
FROM post_attributes
WHERE name IN ('title', 'body');
SELECT id, url, created_at, name, value
FROM posts, post_attributes
WHERE posts.id = post_attributes.post_id
ORDER BY id;
```
The idea would be to extract the post number, it's url, the time it was created, the title and body of the blog post from the blogging engine Chyrp, but disregard the other data stored in the same database.
I am thinking that I am going about this in the wrong manner. Would there be a more appropriate function to use? | ```
SELECT posts.id, posts.url, posts.created_at, posts.name, posts.value
FROM posts, post_attributes
WHERE posts.id = post_attributes.post_id
AND post_attributes.name IN ('title', 'body')
ORDER BY id;
```
Add a `post_attributes.*` to the end if you want all the fields from post attributes. | Are you looking for this:
```
SELECT id, url, created_at, name, value, post_attributes.*
FROM posts, post_attributes
WHERE posts.id = post_attributes.post_id
AND name IN ('title', 'body')
ORDER BY id;
``` | Combining two MySQL Queries (One to select contents of another) | [
"",
"sql",
"mysql",
""
] |
Any idea how to get the DatePicker to appear at the end of the associated text box instead of directly below it? What tends to happen is that the text box is towards the bottom of the page and the DatePicker shifts up to account for it and totally covers the text box. If the user wants to type the date instead of pick it, they can't. I'd rather have it appear just after the text box so it doesn't matter how it adjusts vertically.
Any idea how to control the positioning? I didn't see any settings for the widget, and I haven't had any luck tweaking the CSS settings, but I could easily be missing something. | The accepted answer for this question is actually not for the jQuery UI Datepicker. To change the position of the jQuery UI Datepicker just modify .ui-datepicker in the css file. The size of the Datepicker can also be changed in this way, just adjust the font size. | Here's what I'm using:
```
$('input.date').datepicker({
beforeShow: function(input, inst) {
inst.dpDiv.css({
marginTop: -input.offsetHeight + 'px',
marginLeft: input.offsetWidth + 'px'
});
}
});
```
You may also want to add a bit more to the left margin so it's not right up against the input field. | How to change the pop-up position of the jQuery DatePicker control | [
"",
"javascript",
"jquery",
"jquery-ui",
"jquery-ui-datepicker",
""
] |
I've been doing mainly SQL and front-end HTML/CSS stuff for the past 4 years. I've done a quite a bit of (procedural) coding in a BASIC-like language, too. I do not have formal CS training (I have an econ degree).
Now I'm switching gears to OOP in C# .NET full-time. In order to ramp up, I've been reading about fundamental CS topics (e.g., data structures, algorithms, big-O notation) mainly on StackOverflow and Wikipedia. I've also read through sections of Code Complete 2, Refactoring, and Head First Design Patterns.
I get the feeling, however, that my approach to becoming a developer is somewhat backwards. I feel like I need to familiarize myself with the available tools in C# and .NET *before* I can truly benefit from learning about how best to apply them.
The part I think I'm missing is sitting down and getting familiar with the .NET framework by actually doing some programming. I need to get exposure to the day-to-day tasks that go into building a real application.
Since I don't have a mentor, I was wondering if anyone can suggest a book or website that guides beginner programmers through building a (somewhat) real .NET application as a way to teach them the fundamentals.
Thanks! | <http://www.asp.net/learn/mvc-videos/>
storefront covers everything from design to testing. Should get you started quickly.
<http://codebetter.com/blogs/karlseguin/archive/2008/06/24/foundations-of-programming-ebook.aspx>
Shows some basic concepts but they are very useful. Includes a sample app to learn from.
Finally,
<http://weblogs.asp.net/Scottgu/>
ScottGu's blog is full of useful real-world examples and has a ton of links.
And one more note, the book BlueJ offers some great insight into OO if you are new to it.
<http://www.bluej.org/> | I am in a similar position as you and was looking for how a professional would go about designing and implementing a small program from start to finish. I found these two useful resources:
Rob Conery has a [series of blog posts](http://blog.wekeroad.com/category/mvc-storefront/page/4) where he takes you through how he designed an eCommerce site using ASP.NET MVC.
In a similar fashion, Stephen Walther [builds a forum](http://stephenwalther.com/blog/archive/2008/09/05/asp-net-mvc-application-building-forums-1-create-the-perfect-application.aspx) using ASP.NET MVC | Learning to build real-world .NET apps by example | [
"",
"c#",
".net",
""
] |
Little silly question, but got stuck for a long time.
I have written two classes one which is a Form (TreeDisplay class) and other which contains buiseness logic (MyTreeNode class).
TreeDisplay class contains browse button to select a file pass it to a method *initiatingTree(string filename)* which is in MyTreeNode class.
Now I have to pass this string parameter filename to MyTreeNode class. When I run my code the XML file which I have selected is shown in the textbox but not in treeview.
I have written the part of code but it is throwing NullReferenceException(Object reference not set to an instance of an object).
When the whole code was writeen in Form.cs the code was running successfully but on separating the business logic the exception has occured.
Can you please tell me where I am wrong?
This is the code in Browse button of TreeDisplay class (My main form):
```
if (open.ShowDialog(this) == DialogResult.OK)
{
txtFileName.Text = open.FileName;
MytreeNodeClass treenodeClass = new MytreeNodeClass();
treenodeClass.initiatingTree(open.FileName,treeView1);
}
```
Here is the code of initiatingTree() in my MyTreeNode class:
```
public class MytreeNodeClass
{
private readonly System.Windows.Forms.TextBox txtFileName;
private TreeView treeView1;
private readonly ToolStripStatusLabel toolStripStatusLabel1;
public string Filename
{
get { return filename; }
}
protected string filename;
public MytreeNodeClass()
{
}
public void initiatingTree(string nameofFile,TreeView treeView1)
{
try
{
//Create XML document & load the XML file.
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(nameofFile);
treeView1 = new System.Windows.Forms.TreeView();
treeView1.Nodes.Clear();
if (xmlDocument.DocumentElement != null)
{
TreeNode treeNodedoc = new TreeNode(xmlDocument.DocumentElement.Name);
treeView1.Nodes.Add(treeNodedoc);
}
```
On using breakpoint treeView1.Nodes.Clear(), the code comes out from this line and enters the catch block throwing NullReferenceException.
Please help to find root cause of exception. Thanks. | What is the value of treeView1 at your breakpoint?
I suggest this may be null, as the reference isn't available in your Business Logic Layer.
---
Updated with sample code:
```
public void initiatingTree(string nameofFile, TreeView treeView1)
{
try
{
//Create XML document & load the XML file.
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(nameofFile);
treeView1.Nodes.Clear();
if (xmlDocument.DocumentElement != null)
{
TreeNode treeNodedoc = new TreeNode(xmlDocument.DocumentElement.Name);
treeView1.Nodes.Add(treeNodedoc);
}
}
}
```
and where you call this:
```
if (open.ShowDialog(this) == DialogResult.OK)
{
txtFileName.Text = open.FileName;
MytreeNodeClass treenodeClass = new MytreeNodeClass();
treenodeClass.initiatingTree(open.FileName, treeView1);
}
``` | As c.k said.
You don't have access to the usercontrols from your business layer as a standard.
May i suggest that you keep you control code in the gui code behind for simplicity.
An example how to sort your code
(Gui Layer) Codebehind for control interaction
Business Layer for data manipulation
Data Layer for database manipulations and such | How to pass string parameter of a method from one class to another class in same namespace? | [
"",
"c#",
"winforms",
"class",
""
] |
I am trying to determine what the best way is to find variations of a first name in a database. For example, I search for Bill Smith. I would like it return "Bill Smith", obviously, but I would also like it to return "William Smith", or "Billy Smith", or even "Willy Smith". My initial thought was to build a first name hierarchy, but I do not know where I could obtain such data, if it even exists.
Since users can search the directory, I thought this would be a key feature. For example, people I went to school with called me Joe, but I always go by Joseph now. So, I was looking at doing a phonetic search on the last name, either with NYSIIS or Double Metaphone and then searching on the first name using this name heirarchy. Is there a better way to do this - maybe some sort of graded relevance using a full text search on the full name instead of a two part search on the first and last name? Part of me thinks that if I stored a name as a single value instead of multiple values, it might facilitate more search options at the expense of being able to address a user by the first name.
As far as platform, I am using SQL Server 2005 - however, I don't have a problem shifting some of the matching into the code; for example, pre-seeding the phonetic keys for a user, since they wouldn't change.
Any thoughts or guidance would be appreciated. Countless searches have pretty much turned up empty. Thanks!
**Edit: It seems that there are two very distinct camps on the functionality and I am definitely sitting in the middle right now. I could see the argument of a full-text search - most likely done with a lack of data normalization, and a multi-part approach that uses different criteria for different parts of the name.**
**The problem ultimately comes down to user intent. The Bill / William example is a good one, because it shows the mutation of a first name based upon the formality of the usage. I think that building a name hierarchy is the more accurate (and extensible) solution, but is going to be far more complex. The fuzzy search approach is easier to implement at the expense of accuracy. Is this a fair comparison?**
**Resolution: Upon doing some tests, I have determined to go with an approach where the initial registration will take a full name and I will split it out into multiple fields (forename, surname, middle, suffix, etc.). Since I am sure that it won't be perfect, I will allow the user to edit the "parts", including adding a maiden or alternate name. As far as searching goes, with either solution I am going to need to maintain what variations exists, either in a database table, or as a thesaurus. Neither have an advantage over the other in this case. I think it is going to come down to performance, and I will have to actually run some benchmarks to determine which is best. Thank you, everyone, for your input!** | No, Full Text searches will not help to solve your problem.
I think you might want to take a look at some of the following links: (Funny, no one mentioned SoundEx till now)
* [SoundEx - MSDN](http://msdn.microsoft.com/en-us/library/ms187384.aspx)
* [SoundEx - Google results](http://www.google.com/search?q=soundex+sql)
* [InformIT - Tolerant Search algorithms](http://www.informit.com/articles/article.aspx?p=24691)
Basically SoundEx allows you to evaluate the level of similarity in similar sounding words. The function is also available on SQL 2005.
As a side issue, instead of returning similar results, it might prove more intuitive to the user to use a AJAX based script to deliver similar sounding names before the user initiates his/her search. That way you can show the user "similar names" or "did you mean..." kind of data. | In my opinion you should either do a feature *right* and make it *complete*, or you should leave it off to avoid building a half-assed intelligence into a computer program that still gets it wrong most of the time (["Looks like you're writing a letter"](http://en.wikipedia.org/wiki/Office_Assistant), anyone?).
In case of human names, a computer will get it wrong most of the time, doing it right and complete is impossible, IMHO. Maybe you can hack something that does the most common English names. But actually, the intelligence to look for both "Bill" and "William" is built into almost any English speaking person - I would leave it to them to connect the dots. | First Name Variations in a Database | [
"",
"sql",
"sql-server",
"algorithm",
"database-design",
"data-structures",
""
] |
I was wondering if anyone could spot what is wrong with my structure declaration and use. At the moment I have a structure and wish to store float array as one of it's members.
### My code:
```
struct Player{
float x[12];
float y[12];
float red,green,blue;
float r_leg, l_leg;
int poly[3];
bool up,down;
};
```
I then tried filling the struct:
```
float xcords[12] = {1,1,1,1,1,1,1,1,1,1,1,1 };
float ycords[12] = {1,1,1,1,1,1,1,1,1,1,1,1 };
Player player = {xcords,ycords,1,1,1,2,2,true,true};
```
### Error:
```
1>.\template_with_console.cpp(35) : error C2440: 'initializing' : cannot convert from 'float [12]' to 'float'
1> There is no context in which this conversion is possible
1>.\template_with_console.cpp(35) : error C2440: 'initializing' : cannot convert from 'float [12]' to 'float'
1> There is no context in which this conversion is possible
``` | Arrays decay to pointer-to-first-element of the array in most contexts as is the case with `xcords` and `ycords`. You cannot initialize the struct like this. So, you have to initialize the members explicitly:
```
Player player = {
{1,1,1,1,1,1,1,1,1,1,1,1 }, // xcords
{1,1,1,1,1,1,1,1,1,1,1,1 }, // ycords
1,1,1, // red, green, blue
2,2, // right, left
{0,1,2}, // poly[3] -- missing?
true,true}; // up, down
```
You are also missing initializers for poly[3] if I understand correctly. Put in the appropriate values. Otherwise there will be default initialization -- is that what you want? | Try
```
Player player = {{1,1,1,1,1,1,1,1,1,1,1,1 },
{1,1,1,1,1,1,1,1,1,1,1,1 },
1,1,1,
2,2,
{},
true,true};
``` | Help with declaring C++ structure, with a float array as one of its members | [
"",
"c++",
"arrays",
"structure",
"declaration",
""
] |
I have the following codes to create chart graphics by dojox.charting:
```
function createChart() {
var node = dojo.byId("surfaceDiv");
while (node.hasChildNodes())
{
node.removeChild(node.lastChild); // remove all the children graphics
}
var nodes = "<div id='chart1' style='width: 10px; height: 10px;'></div><div id='legend1' ></div>";
dojo.html.set(node, nodes);
var nodeChart = dojo.byId("chart1");
var nodeLegend = dojo.byId("legend1");
var chart1 = new dojox.charting.Chart2D(nodeChart);
// set chart types and point series
chart1.render();
// now to add legend:
var legendNode = new dojox.charting.widget.Legent(
{chart: chart1}, nodeLegend.id));
}
```
The function works fine for the first call; however, if it is called again, the chart is displayed OK, but the legend is not displayed. In firebug, I noticed there is an error saying "Tried to register widget with id==legend1 but that id is already registered" in manager.xd.js (line 8). It looks like that somewhere in dojox's library cached the previous legend object with the same id.
I guess I have to clean any legend previously registered or cached. How can I do that?
By the way, in my html page, I have several ancor links to call JavaScript functions to draw different graphics in a div node with id="surfaceDiv", and the legend node" is the next div with id="legendDiv". Therefore, the above function can be called again. | I think that is a bug in dojox.charting.widget.Legend(...). What I did was to clean all the graphics and legend dom elements under div "surfaceDiv", and add new div "chart1" for chart and div "legend1" as legend. The chart works OK but not legend. I have the following anchor link call to the function in my html:
```
....
<a href="javascript:createChart();">Curve chart</a>
....
```
As a result, the function createChart() can be called more than once within the same web page session. The first time the chart and legend were displayed but the legend was missing in the subsequent calls or clicks.
To work around the problem or bug, I have to set legend ID dynamically with different values. Any cached legend id value within dojox.charting.widget.Legend(...) will not be conflict with new ids. Here is the codes:
```
var legendCount = 0; // global value
function createChart() {
var node = dojo.byId("surfaceDiv");
while (node.hasChildNodes())
{
node.removeChild(node.lastChild); // remove all the children graphics
}
var legendID = "legend" + legendCount++;
var nodes = "<div id='chart1' style='width: 10px; height: 10px;'></div>" +
"<div id='" + legendID + "' ></div>"; // Set legend ID dynamically
dojo.html.set(node, nodes);
var nodeChart = dojo.byId("chart1");
var nodeLegend = dojo.byId(legendID);
var chart1 = new dojox.charting.Chart2D(nodeChart);
// set chart types and point series
chart1.render();
// now to add legend:
var legendNode = new dojox.charting.widget.Legent(
{chart: chart1}, nodeLegend.id)); // no more conflict legend's ID
}
```
I tested my codes and html page again. Legend is displayed every time! | I'm using dojox 1.3.0 and found the following works fine for me (legend
is a global var) without any errors:
```
if (legend != undefined) {
legend.destroyRecursive(true);
}
legend = new dojox.charting.widget.Legend({chart: chart1,horizontal: true}, 'legend');
//or try this
var myObj = new dojoObject(...);
...
// do whatever we want with it
...
// now we don't need it and we want to dispose of it
myObj.destroy();
delete myObj;
```
In this case, the legend is destroyed before it's recreated.
Here is another link on this subject: <http://www.dojotoolkit.org/forum/dojox-dojox/dojox-support/how-unregister-legend-dojox-charting> | How to unregister legend in dojox.charting? | [
"",
"javascript",
"dojo",
""
] |
If i try with BitConverter,it requires a byte array and i don't have that.I have a Int32 and i want to convert it to UInt32.
In C++ there was no problem with that. | A simple cast is all you need. Since it's possible to lose precision doing this, the conversion is explicit.
```
long x = 10;
ulong y = (ulong)x;
``` | Try:
```
Convert.ToUInt32()
``` | C#: How to convert long to ulong | [
"",
"c#",
"long-integer",
"ulong",
""
] |
I'm working with the [Skype4COM.dll COM API](https://developer.skype.com/Docs/Skype4COM) using C# and it works very well for all of the communication functionality we need. We are trying to put an easier to use interface on top of Skype that is baked into our application.
My trouble lies in controlling or disabling which Skype windows to use and not use. The only Skype window I believe I'll need is the Skype video phone/conference window. I would like to hide and control every other window that Skype can present. I would even like to disable the incoming call dialog window that pops up on incoming calls, since we'll be presenting our own answer prompt. I'm happy with the API except window management.
With the API, I can see how to enable Windows, but I can't seem to figure out how to hide them, short of hacking a windows message to the Skype app. Am I missing something?
Thanks for your assistance, Kenny | Poking around a bit we found that you can send 'Skype Commands' via
```
skypeobj.SendCommand ( Command cmd );
```
That works pretty well for most of what we need. Here is a [reference on the Skype developer site](https://developer.skype.com/Docs/ApiDoc/Controlling_Skype_user_interface):
Some code:
```
void _SendSkypeCommand ( string cmdToSend )
{
Command cmdSkype = new Command ();
cmdSkype.Blocking = true;
cmdSkype.Timeout = 2000;
cmdSkype.Command = cmdToSend;
Trace.WriteLineIf ( _TracingDetailed, string.Format ( "skype command sent '{0}'", cmdToSend ) );
_skype.SendCommand ( cmdSkype );
}
void _hideSkypeWindows ()
{
_SendSkypeCommand ( "SET SILENT_MODE ON" );
_SendSkypeCommand ( "SET WINDOWSTATE HIDDEN" );
}
``` | Unfortunately, the interface doesn't actually give you control over the actual windows, only methods to display and modify them (through wrappers).
As you said, you will have to get the handle of the window somehow and then send a message to hide it. | Controlling Skype via its Skype4COM.dll COM API | [
"",
"c#",
"com",
"skype",
""
] |
I have an HTML file with a couple of external JavaScript files. Here's an example, somewhat simplified from the real HTML and JavaScript files:
```
<head>
<title>Control Page</title>
<script language="JavaScript" src="control.js"></script>
<script language="JavaScript">
var myWindow;
var controlForm;
function onPageLoad() {
myWindow = document.getElementById('iframe1');
controlForm = document.getElementById('ControlForm');
}
</script>
</head>
<body onLoad="onPageLoad()">
....
</body>
</html>
```
and then in my JavaScript file `control.js`:
```
function messageArrival(message) {
chatwindow.contentWindow.document.write(message)
}
function makeNetMeetingCall() {
controlForm.Status.value = ....
}
....
```
My question: When I validate the external JavaScript file, it complains about the variables that are defined in the main HTML file because they aren't declared anywhere in the `*.js` file. For example, MyEclipse's JavaScript editor complains that it sees variables used that are not defined in any visible scope. How can I declare these variables in the JavaScript file so that it's clear the variables are expected to be defined externally, something similar to "`extern`" in C. | This sounds more like an issue with MyEclipse's JS editor than your JS.
Unfortunately, I'm not familiar with MyEclipse. However, I do know of a good JS validator, [JSLint](http://www.jslint.com/), which accounts for global variables by having you define them in the comments:
```
/*global getElementByAttribute, breakCycles, hanoi */
``` | You could declare the variables in the global scope of your control.js file.
```
var controlForm;
function makeNetMeetingCall() {
// ...
}
```
this won't interfere with the code that finally defines these objects, as it executes first. But even if it didn't, without an initializer it wouldn't overwrite anything.
If you need proof about the overwriting, just did this in the JS shell:
```
$ js
js> var x = 1;
js> print( x );
1
js> var x;
js> print( x );
1
js>
``` | How can I get my JavaScript, referencing a var defined externally, to validate? | [
"",
"javascript",
"validation",
"myeclipse",
""
] |
say I have the following declarations:
```
public enum Complexity { Low = 0, Normal = 1, Medium = 2, High = 3 }
public enum Priority { Normal = 1, Medium = 2, High = 3, Urgent = 4 }
```
and I want to code it so that I could get the enum value (not the index, like I earlier mentioned):
```
//should store the value of the Complexity enum member Normal, which is 1
int complexityValueToStore = EnumHelper.GetEnumMemberValue(Complexity.Normal);
//should store the value 4
int priorityValueToStore = EnumHelper.GetEnumMemberValue(Priority.Urgent);
```
How should this reusable function look like?
tia!
-ren | **Revised answer (after question clarification)**
No, there's nothing cleaner than a cast. It's more informative than a method call, cheaper, shorter etc. It's about as low impact as you could possibly hope for.
Note that if you wanted to write a generic method to do the conversion, you'd have to specify what to convert it to as well: the enum could be based on `byte` or `long` for example. By putting in the cast, you explicitly say what you want to convert it to, and it just does it.
**Original answer**
What do you mean by "index" exactly? Do you mean the numeric value? Just cast to `int`. If you mean "position within enum" you'd have to make sure the values are in numeric order (as that's what `Enum.GetValues` gives - not the declaration order), and then do:
```
public static int GetEnumMemberIndex<T>(T element)
where T : struct
{
T[] values = (T[]) Enum.GetValues(typeof(T));
return Array.IndexOf(values, element);
}
``` | You can find the integer value of an enum by casting:
```
int complexityValueToStore = (int)Complexity.Normal;
``` | C# function that accepts an Enum item and returns the enum value (not the index) | [
"",
"c#",
"function",
"enums",
"generics",
""
] |
I have a bunch of strings that I need to sort. I think a std::vector would be the easiest way to do this. However, I've never used vectors before and so would like some help.
I just need to sort them alphanumerically, nothing special. Indeed, the string::compare function would work.
After that, how can I iterate through them to verify that they're sorted?
Here's what I have so far:
```
std::sort(data.begin(), data.end(), std::string::compare);
for(std::vector<std::string>::iterator i = data.begin(); i != data.end(); ++i)
{
printf("%s\n", i.c_str);
}
``` | You can just do
```
std::sort(data.begin(), data.end());
```
And it will sort your strings. Then go through them checking whether they are in order
```
if(names.empty())
return true; // empty vector sorted correctly
for(std::vector<std::string>::iterator i=names.begin(), j=i+1;
j != names.end();
++i, ++j)
if(*i > *j)
return false;
return true; // sort verified
```
In particular, `std::string::compare` couldn't be used as a comparator, because it doesn't do what `sort` wants it to do: Return true if the first argument is less than the second, and return false otherwise. If you use `sort` like above, it will just use `operator<`, which will do exactly that (i.e `std::string` makes it return `first.compare(second) < 0`). | What is the question exactly? It seems everything is already there.
However, you should probably use `std::cout << *i << std::endl;`
1. `i` is an iterator == pointer to the data in the container, so `*` is needed
2. `c_str()` is a function of `std::string` and not a variable
The problems in your code do not relate to your question?
Some hints for you:
* `std::vector` also overrides `[]` operator, so you can instead save the iterator hassle and use it like an array (iterate from `0` to `vector.size()`).
* You could use `std::set` instead, which has automatically sorting on insertion (binary tree), so you save the extra sorting.
* Using a functor makes your output even more fun: `copy(V.begin(), V.end(), ostream_iterator<std::string>(cout, "\n"));` | How can I build a std::vector<std::string> and then sort them? | [
"",
"c++",
"string",
"sorting",
"vector",
""
] |
What are the best candidates for a precompiled header file? Can I put STL and Boost headers there, even though they have templates? And will that reduce compile times?
Also, what are the best IDE settings to reduce compile times? | The quick answer: the STL and Boost headers do indeed belong in the precompiled header file, even though these header files define template classes.
When generating a precompiled header file, a compiler parses the header text (a significant task!), and converts it into a binary format that is optimised for the compiler's benefit.
Even though the template classes will be instantiated when other .cpp files are compiled, they will be instantiated from information in the precompiled header, which is significantly faster for the compiler to read.
---
*(later addition)*
One thing that you should **not** include in a precompiled header are files that are part of your project and are changed frequently, even if every single .CPP file includes these files.
The reason is this - the generation of the precompiled header can take a long time, because the boost, stl and windows libraries are very large.
You might have a simple file (eg "StringDefs.h") that everything uses. If StringDefs.h is included in stdafx.h, and one developer touches StringDefs.h, then every developer has to wait until the *entire precompiled header* recompiles. It would be much faster if StringDefs.h was left out of the precompiled header, and parsed along with each .CPP file. | One addition to Andrew Shepherd's answer. Use the precompiled header for header files that are external to your project, for files that change infrequently. If you're changing the header files in the current project all the time, it's probably not worth precompiling them. | What to put in precompiled header? (MSVC) | [
"",
"c++",
"visual-c++",
"precompiled-headers",
""
] |
Say you have a very simple data structure:
```
(personId, name)
```
...and you want to store a number of these in a javascript variable. As I see it you have three options:
```
// a single object
var people = {
1 : 'Joe',
3 : 'Sam',
8 : 'Eve'
};
// or, an array of objects
var people = [
{ id: 1, name: 'Joe'},
{ id: 3, name: 'Sam'},
{ id: 8, name: 'Eve'}
];
// or, a combination of the two
var people = {
1 : { id: 1, name: 'Joe'},
3 : { id: 3, name: 'Sam'},
8 : { id: 8, name: 'Eve'}
};
```
The second or third option is obviously the way to go if you have (or expect that you might have) more than one "value" part to store (eg, adding in their age or something), so, for the sake of argument, let's assume that there's never ever going to be any more data values needed in this structure. Which one do you choose and why?
---
**Edit**: The example now shows the most common situation: non-sequential ids. | Each solution has its use cases.
I think the first solution is good if you're trying to define a one-to-one relationship (such as a simple mapping), especially if you need to use the key as a lookup key.
The second solution feels the most robust to me in general, and I'd probably use it if I didn't need a fast lookup key:
* It's self-describing, so you don't
have to depend on anyone using
*people* to know that the key is the id of the user.
* Each object comes self-contained,
which is better for passing the data
elsewhere - instead of two parameters
(id and name) you just pass around
people.
* This is a rare problem, but sometimes
the key values may not be valid to
use as keys. For example, I once
wanted to map string conversions
(e.g., ":" to ">"), but since ":"
isn't a valid variable name I had to
use the second method.
* It's easily extensible, in case
somewhere along the line you need to
add more data to some (or all) users.
(Sorry, I know about your "for
argument's sake" but this is an
important aspect.)
The third would be good if you need fast lookup time + some of the advantages listed above (passing the data around, self-describing). However, if you don't need the fast lookup time, it's a lot more cumbersome. Also, either way, you run the risk of error if the id in the object somehow varies from the id in *people*. | Actually, there is a fourth option:
```
var people = ['Joe', 'Sam', 'Eve'];
```
since your values happen to be consecutive. (Of course, you'll have to add/subtract one --- or just put undefined as the first element).
Personally, I'd go with your (1) or (3), because those will be the quickest to look up someone by ID (O log*n* at worst). If you have to find id 3 in (2), you either can look it up by index (in which case my (4) is ok) or you have to search — O(n).
Clarification: I say O(log*n*) is the worst it could be because, AFAIK, and implementation could decide to use a balanced tree instead of a hash table. A hash table would be O(1), assuming minimal collisions.
*Edit from nickf: I've since changed the example in the OP, so this answer may not make as much sense any more. Apologies.*
## Post-edit
Ok, post-edit, I'd pick option (3). It is extensible (easy to add new attributes), features fast lookups, and can be iterated as well. It also allows you to go from entry back to ID, should you need to.
Option (1) would be useful if (a) you need to save memory; (b) you never need to go from object back to id; (c) you will never extend the data stored (e.g., you can't add the person's last name)
Option (2) is good if you (a) need to preserve ordering; (b) need to iterate all elements; (c) do not need to look up elements by id, unless it is sorted by id (you can do a binary search in O(log*n*). Note, of course, if you need to keep it sorted then you'll pay a cost on insert. | Objects vs arrays in Javascript for key/value pairs | [
"",
"javascript",
"data-structures",
""
] |
In VC++ 2003, I could just save the source file as UTF-8 and all strings were used as is. In other words, the following code would print the strings as is to the console. If the source file was saved as UTF-8 then the output would be UTF-8.
```
printf("Chinese (Traditional)");
printf("中国語 (繁体)");
printf("중국어 (번체)");
printf("Chinês (Tradicional)");
```
I have saved the file in UTF-8 format with the UTF-8 BOM. However compiling with VC2008 results in:
```
warning C4566: character represented by universal-character-name '\uC911'
cannot be represented in the current code page (932)
warning C4566: character represented by universal-character-name '\uAD6D'
cannot be represented in the current code page (932)
etc.
```
The characters causing these warnings are corrupted. The ones that do fit the locale (in this case 932 = Japanese) are converted to the locale encoding, i.e. Shift-JIS.
I cannot find a way to get VC++ 2008 to compile this for me. Note that it doesn't matter what locale I use in the source file. There doesn't appear to be a locale that says "I know what I'm doing, so don't f$%##ng change my string literals". In particular, the useless UTF-8 pseudo-locale doesn't work.
```
#pragma setlocale(".65001")
=> error C2175: '.65001' : invalid locale
```
Neither does "C":
```
#pragma setlocale("C")
=> see warnings above (in particular locale is still 932)
```
It appears that VC2008 forces all characters into the specified (or default) locale, and that locale cannot be UTF-8. I do not want to change the file to use escape strings like "\xbf\x11..." because the same source is compiled using gcc which can quite happily deal with UTF-8 files.
Is there any way to specify that compilation of the source file should leave string literals untouched?
To ask it differently, what compile flags can I use to specify backward compatibility with VC2003 when compiling the source file. i.e. do not change the string literals, use them byte for byte as they are.
**Update**
Thanks for the suggestions, but I want to avoid wchar. Since this app deals with strings in UTF-8 exclusively, using wchar would then require me to convert all strings back into UTF-8 which should be unnecessary. All input, output and internal processing is in UTF-8. It is a simple app that works fine as is on Linux and when compiled with VC2003. I want to be able to compile the same app with VC2008 and have it work.
For this to happen, I need VC2008 to not try to convert it to my local machine's locale (Japanese, 932). I want VC2008 to be backward compatible with VC2003. I want a locale or compiler setting that says strings are used as is, essentially as opaque arrays of char, or as UTF-8. It looks like I might be stuck with VC2003 and gcc though, VC2008 is trying to be too smart in this instance. | Update:
I've decided that there is no guaranteed way to do this. The solution that I present below works for English version VC2003, but fails when compiling with Japanese version VC2003 (or perhaps it is Japanese OS). In any case, it cannot be depended on to work. Note that even declaring everything as L"" strings didn't work (and is painful in gcc as described below).
Instead I believe that you just need to bite the bullet and move all text into a data file and load it from there. I am now storing and accessing the text in INI files via [SimpleIni](http://code.jellycan.com/simpleini/) (cross-platform INI-file library). At least there is a guarantee that it works as all text is out of the program.
Original:
I'm answering this myself since only Evan appeared to understand the problem. The answers regarding what Unicode is and how to use wchar\_t are not relevant for this problem as this is not about internationalization, nor a misunderstanding of Unicode, character encodings. I appreciate your attempt to help though, apologies if I wasn't clear enough.
The problem is that I have source files that need to be cross-compiled under a variety of platforms and compilers. The program does UTF-8 processing. It doesn't care about any other encodings. I want to have string literals in UTF-8 like currently works with gcc and vc2003. How do I do it with VC2008? (i.e. backward compatible solution).
This is what I have found:
gcc (v4.3.2 20081105):
* string literals are used as is (raw strings)
* supports UTF-8 encoded source files
* source files must not have a UTF-8 BOM
vc2003:
* string literals are used as is (raw strings)
* supports UTF-8 encoded source files
* source files may or may not have a UTF-8 BOM (it doesn't matter)
vc2005+:
* string literals are massaged by the compiler (no raw strings)
* char string literals are re-encoded to a specified locale
* UTF-8 is not supported as a target locale
* source files must have a UTF-8 BOM
So, the simple answer is that for this particular purpose, VC2005+ is broken and does not supply a backward compatible compile path. The only way to get Unicode strings into the compiled program is via UTF-8 + BOM + wchar which means that I need to convert all strings back to UTF-8 at time of use.
There isn't any simple cross-platform method of converting wchar to UTF-8, for instance, what size and encoding is the wchar in? On Windows, UTF-16. On other platforms? It varies. See the [ICU project](http://icu-project.org/docs/papers/unicode_wchar_t.html) for some details.
In the end I decided that I will avoid the conversion cost on all compilers other than vc2005+ with source like the following.
```
#if defined(_MSC_VER) && _MSC_VER > 1310
// Visual C++ 2005 and later require the source files in UTF-8, and all strings
// to be encoded as wchar_t otherwise the strings will be converted into the
// local multibyte encoding and cause errors. To use a wchar_t as UTF-8, these
// strings then need to be convert back to UTF-8. This function is just a rough
// example of how to do this.
# define utf8(str) ConvertToUTF8(L##str)
const char * ConvertToUTF8(const wchar_t * pStr) {
static char szBuf[1024];
WideCharToMultiByte(CP_UTF8, 0, pStr, -1, szBuf, sizeof(szBuf), NULL, NULL);
return szBuf;
}
#else
// Visual C++ 2003 and gcc will use the string literals as is, so the files
// should be saved as UTF-8. gcc requires the files to not have a UTF-8 BOM.
# define utf8(str) str
#endif
```
Note that this code is just a simplified example. Production use would need to clean it up in a variety of ways (thread-safety, error checking, buffer size checks, etc).
This is used like the following code. It compiles cleanly and works correctly in my tests on gcc, vc2003, and vc2008:
```
std::string mText;
mText = utf8("Chinese (Traditional)");
mText = utf8("中国語 (繁体)");
mText = utf8("중국어 (번체)");
mText = utf8("Chinês (Tradicional)");
``` | While it is probably better to use wide strings and then convert as needed to UTF-8. I think your best bet is to as you have mentioned use hex escapes in the strings. Like suppose you wanted code point `\uC911`, you could just do this.
```
const char *str = "\xEC\xA4\x91";
```
I believe this will work just fine, just isn't very readable, so if you do this, please comment it to explain. | How to create a UTF-8 string literal in Visual C++ 2008 | [
"",
"c++",
"visual-c++",
"utf-8",
""
] |
My compilers class is creating a language that we intend to compile to Java Bytecode. We have made plenty of progress and are nearing the time where it's time for code generation.
We are having problems locating information on how to create .class files from our compiler. Do you have any resources that can give us some assistance? We already have plenty of documentation on the instruction set, but need information on how to directly fill out the class file/the writing of hex.
We do not need information or suggestions on decompiling the .class files.
Even a simple example of writing out a .class file from scratch would be excellent.
**The JVM spec is not what we're after.** What we really need is an example or a walkthrough. | The VM Spec: [The Class File Format](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html) and the [The Java Virtual Machine Instruction Set](http://java.sun.com/docs/books/jvms/second_edition/html/Instructions.doc.html) should do it.
You might look at the Byte Code Engineering Library ([BCEL](http://jakarta.apache.org/bcel/)) for some inspiration as well as [Findbugs](http://findbugs.sourceforge.net/) (it has to read/understand class files). | There are a number of projects out there that provide a high level interface to creating Java class files without you having to write the class files yourself. Take a look at the following:
* ASM - <http://asm.objectweb.org/>
* BCEL - <http://jakarta.apache.org/bcel/>
* Trove - <http://teatrove.sourceforge.net/trove.html>
All provide an API to create class files. You could always look at the code they've written to do this and write some similar code for your compiler although I would imagine that it's a fair amount of work.
With BCEL take a look at ClassGen, that should enable you to write out class files in the format you want, a simple example follows:
```
ClassGen cg = new ClassGen("HelloWorld", "java.lang.Object",
"<generated>", ACC_PUBLIC | ACC_SUPER,
null);
``` | Compile to java bytecode (without using Java) | [
"",
"java",
"compiler-construction",
"bytecode",
""
] |
Not sure how to word this and so am not having much luck in Google searches...
I need to calculate a value for a string of numbers.
Example.
A user types in "1.00 + 2.00 - 0.50" into a text field. The function should be able to take that string and calculate the result to return $2.50.
Anyone have a way to do this in their bag of tricks? | If it's actually a mathematical operation you may just use eval, not sure that's what you want though :
```
document.write(eval("1.00 + 2.00 - 0.50"));
``` | Theo T's answer looks like the most straightforward way, but if you need to write your own simple parser, you can start by [splitting](http://www.w3schools.com/jsref/jsref_split.asp) the string and looking for your operators in the output. | JavaScript function to add a string of numbers | [
"",
"javascript",
""
] |
Since both the java implementation (`OpenJDK`) and Android's virtual machine DalvikVM are opensource it must be possible to implement Sun's JavaVM on top Google's DalvikVM. This would make it possible to run JVM based apps and languages (`Clojure, Jython`) out-of-the-box on the android.
Is there an ongoing effort to produce such an implementation of the Sun JVM? | The OpenJDK makes use of native code so it would be a non-trivial port... there is at least one VM ([JikesRVM](http://jikesrvm.org/)) that is written in Java, unfortunately it is not a completely working implementation of Java.
Since DalvikVM runs classes that were converted from .class files it should be possible to convert the classes over. Then the "only" issue is when languages generate bytecode on the fly - for that it would require the extra step of converting the generated bytecode over to the DalvikVM format while the program is running on the DalvikVM.
Hmmm.... sort of a JITT (Just In Time Translator) that covertes class files to a DalvikVM files at runtime on the phone. I wonder how slow that would be. | Porting OpenJDK to Android platform is possible. There are effort like : Shark, Zero and caciocavallo that vastly ease the port process (= no ASM, simple AWT peer). Plus Android is nothing but a linux kernel behind. The only question is when will it be done by anybody ?
By the way, both iphones and android phones got Jazelle compatible processor, somebody with very strong processor hacking skills would be very welcome to add Jazelle support to OpenJDK.
Doing so, we could choose between : very light resource acceleration (Jazelle) and JIT ;-)
About iPhone, it is the same thing : a port is possible. Only Apple has put a section in the the iPhone license that clearly forbid VM usage. As per European law, to me, this license section is unlegal. Two reasons : You can not force/link buy of two of your product. Here I tune and Iphones are linked. You can not refuse to sell something that you can sell. Here as soon as a VM would be build for iPhone, if it is refused to be put on the iTune store, then this point will apply. Is there anybody that want to chalenge Apple licence legality on earth ? I don't think so, unhappy people will be flying to Android or any other platform. | Running Java bytecode on the Android - Sun JVM on top of DalvikVM | [
"",
"java",
"android",
"clojure",
"jvm",
""
] |
I have bound an ASP.net GridView to a collection of anonymous types.
How can I reference one of the properties of the anonymous types in the RowDataBound event handler?
I am already aware of the way to cast the anonymous type like this:
```
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var AnonObj = Cast(e.Row.DataItem,
new { StringProperty = "", BoolProperty = false, IntProperty = 0 });
if (AnonObj.BoolProperty)
{
e.Row.Style.Add(HtmlTextWriterStyle.Color, "Red");
}
}
}
T Cast<T>(object obj, T type)
{
return (T)obj;
}
```
I think most would say this is messy, even though it does work. In my real code, I have more than 3 properties and I would have to update code in two places anytime I added or reordered the properties of my anonymous type.
Is there a better way to tell e.Row.DataItem that it has a specific property of a specific type and force the object to give me that value (besides creating a class)? | The way you are using (cast by example) is messy and **very** brittle - I **really** don't recommend it (if you add a property, or name them in a different order, it'll break; etc). The better approach is to use your own named type in the projection. | Look into using reflection.
Example:
```
object o = e.Row.DataItem;
Type t = o.GetType();
PropertyInfo pi = t.GetProperty("StringProperty");
if (pi != null && pi.PropertyType == typeof(string))
{
// the property exists!
string s = pi.GetValue(o, null) as string;
// we have the value
// insert your code here
// PROFIT! :)
}
```
Error-checking and optimization left as an exercise to the reader. | .net Databinding - Referencing Anonymous Type Properties | [
"",
"c#",
"linq",
"data-binding",
"reflection",
"anonymous-types",
""
] |
I am trying to use Twitter OAuth and my `POST` requests are failing with a `401` (`Invalid OAuth Request`) error.
For example, if I want to post a new status update, I am sending a HTTP `POST` request to `https://twitter.com/statuses/update.json` with the following parameters -
```
status=Testing&oauth_version=1.0&oauth_token=xxx&
oauth_nonce=xxx&oauth_timestamp=xxx&oauth_signature=xxx&
oauth_consumer_key=xxx&in_reply_to=xxx&oauth_signature_method=HMAC-SHA1`
```
My `GET` requests are all working fine. I can see on the mailing lists that a lot of people have had identical problems but I could not find a solution anywhere.
I am using the `oauth.py` Python library. | Most likely, the signature is invalid. You must follow the OAuth spec on how to generate the signature( normalized parameters, URLencoding, and cosumerSecret&oauthScret. More on this later ...... | I just finished implementing twitter OAuth API from scratch using Java. Get and post requests work OK. You can use this page <http://www.hueniverse.com/hueniverse/2008/10/beginners-gui-1.html> to check signature and HTTP headers. Just enter your keys and tokens and check output. It seems twitter works exactly as described on this post. Be careful with spaces and UTF-8 symbols, for example Java encodes space as "+" but OAuth requires %20 | Getting 401 on Twitter OAuth POST requests | [
"",
"python",
"web-services",
"twitter",
"rest",
"oauth",
""
] |
Currently I am studying for my Java test. Whist studying I've come across a small problem.
In this for loop:
```
for ( int i=1; i <= 3 ; i++ ) {
for (int j=1; j <= 3 ; j++ ) {
System.out.println( i + " " + j );
}
}
```
The output is:
```
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
```
My problem is, I don't understand it. When I read this code I keep thinking it should look like this:
```
1 1
2 2
3 3
```
Why is this not the case? | Each iteration of i, you're starting a completely new iteration of j.
So, you start with i==1, then j==1,2,3 in a loop. Then i==2, then j==1,2,3 in a loop, etc.
Step through it one step at a time, and it will make sense. | What you have is one loop inside of another. Think of it like the minute hand and the hour hand on a clock. The minute hand is going to go around (1,2,3,4...59) while the hour hand is still on 1. So, if we treat hours as i, and minutes as j, we have:
1 1
1 2
1 3
...
1 60
And then the hours change to 2, and the minute hand keeps going around:
2 1
2 2
2 3
...
2 60
And we finish once we get to
12 1
12 2
12 3
...
12 60
which is where the loop ends. Your example is much like this.
*(For the pedantic, I know it's zero-based, but in order to illustrate, this may be easier to understand)* | Simple nested for loop example | [
"",
"java",
"for-loop",
""
] |
I'm starting to mess with ASP.NET MVC and came across the issue of wanting to do some basic Paging. So I used this simple Linq statement (using the Northwind Database) to get 10 items for a specific page:
```
var q = (from p in db.Orders
orderby p.OrderDate descending
select p).Skip(currentPage * pageAmount).Take(pageAmount);
```
It works well, but then when I debugged, I was curious what the actual SQL was generated by Linq to Sql. This was the output:
```
SELECT [t1].[OrderID], [t1].[CustomerID], [t1].[EmployeeID], [t1].[OrderDate], [t1].[RequiredDate], [t1].[ShippedDate], [t1].[ShipVia], [t1].[Freight], [t1].[ShipName], [t1].[ShipAddress], [t1].[ShipCity], [t1].[ShipRegion], [t1].[ShipPostalCode], [t1].[ShipCountry]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY [t0].[OrderDate] DESC) AS [ROW_NUMBER], [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]
FROM [dbo].[Orders] AS [t0]
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]
```
Now I'm not SQL expert at all, which is why I've never seen the "OVER" clause. I'm just curious from a high level what exactly it does and when is it used? | It tells the `ROW_NUMBER` function how to assign a number to each row, based on the expression within the parentheses. The rows don't actually get sorted according to this number within the subquery, though. That's what the sort in the outer query is for. | `ROW_NUMBER() OVER`
> returns the sequential number of a row
> within a partition of a result set,
> starting at 1 for the first row in
> each partition.
In your example, the resultset is being ordered by descending `OrderDate` and then the `ROW_NUMBER` function is applied to it. The resultset returned is only going to be where `ROW_NUMBER is BETWEEN (@p0 + 1) and (@p0 + @p1)`
As DOK has said, `OVER` clause is not used on it's own, but in conjunction with aggregate and ranking window functions.
From [MSDN](http://msdn.microsoft.com/en-us/library/ms189461.aspx) -
> **OVER Clause (Transact-SQL)**
>
> Determines the partitioning and
> ordering of the rowset before the
> associated window function is applied. | What exactly does the "Over" Clause in T-Sql do? | [
"",
"sql",
"asp.net-mvc",
"over-clause",
""
] |
I've got a code like this:
```
public abstract class Base
{
// is going to be used in deriving classes
// let's assume foo is threadsafe
protected static readonly Foo StaticFoo = new Foo();
}
```
Visual Studio 2008's Code Analysis pops up this message:
> `CA2104 : Microsoft.Security : Remove the read-only designation from 'Base.StaticFoo' or change the field to one that is an immutable reference type. If the reference type 'Foo' is, in fact, immutable, exclude this message.`
Is my design instrinsically flawed, or can i add a `[SuppressMessage]` in the source? | The problem is that it gives the wrong impression - it makes it look like the value can't change, when actually it's only the *field* value that can't change, rather than the object. I think the code analysis is being overly cautious here - there are plenty of places where you might want a mutable type stored in a readonly field, particularly if it's private, initialized in a static initializer and then never mutated within your code.
While the field is protected, however, there's more of a risk of derived classes abusing it. Personally I like all my fields to be private. On the other hand, I don't know your code - it could be that you've weighed that up against the possibilities and decided it's the right thing to do.
If `Foo` really is thread-safe, there's less to worry about, other than the general impression of immutability given by the fact that the field is readonly. I'd disable the warning for that line, and add a comment to emphasize that the object is mutable even though the field is readonly. | Is the Foo type immutable?
If not, is your intention to use only this one Foo object, but to be able to alter its properties? If this is the case, then the warning is simply saying that the readonly keyword is misleading. There is no compilation error - the reference to the object is readonly, and that is what you have declared to the compiler. However, what you have declared to other developers is that StaticFoo is readonly which implies that it will never change.
So, you have a choice, as it says. To eliminate this warning, either remove the readonly keywoard, or add a SuppressMessage attribute. Alternatively, look at the design of your code. Would implementing Foo as a singleton pattern be more appropriate for example? | C# CA2104 - Automated Code Analysis dislikes static readonly mutable types | [
"",
"c#",
"visual-studio-2008",
"code-analysis",
""
] |
Besides [www.asp.net/learn/](http://www.asp.net/learn/), what other sites have good free video tutorials for ASP.net(c#) and everything related to asp.net and the Visual Studio IDE. | Check out the [Official site](http://www.asp.net/LEARN/). It has loads of video tutorials.
A quick google shows up the [BestTechVideos](http://www.bestechvideos.com/category/development/aspnet) site which aggregates tech videos. | [Channel9](http://channel9.msdn.com/) has some great asp.net screencasts. I was also able to somewhat filter the screencasts by using [this search](http://channel9.msdn.com/Search/Default.aspx?Term=screencast%20asp.net). | What are some sites with good free video tutorials on ASP.NET (C#)? | [
"",
"c#",
"asp.net",
"video",
""
] |
Is there a Javascript or jQuery method to minimize the current browser window? | There is no way to minimize the browser window within javascript.
There are ways to change the size of the window, but no true minimization (nice word) | No, there isn't.
However, depending on what you're doing and which browsers you're targeting, you could play around with the blur and focus events of the window to achieve similar effect. | Minimize browser window using Javascript | [
"",
"javascript",
"jquery",
"browser",
""
] |
i have a rule which:
```
RewriteRule ^cat_ap~([^~]+)~(.*)\.htm$ /urban/cat_ap.php?$1=$2 [L]
```
goes to cat\_ap.php?nid=xxxxxxx
now I have to add some other support.
```
cat_ap~pnid~290~nid~96666~posters~Sports.htm
```
needs to resolve to cat\_ap.php?pnid=290&nid=96666 (I'm not concerned with the end of the link though I do need it in there for legacy paid search traffic).
Also, I need to get a page\_num out of the link to calculate pagination.
```
cat_ap~PageNum_GetProduct~10~nid~290.htm needs to resolve to cat_ap.php?PageNum_GetProduct=10&nid=290
```
I kind of need to encompass all these scenarios either into a single or multiple rules.
Any ideas? I'm reading up on this right now but am stuck.
Thanks | In this kind of scenario i'd suggest to use the rule **RewriteRule ^cat\_ap(~.\*).htm$ /urban/cat\_ap.php?$1 [L]** in order to catch all possible combination and decompose the string inside your php application.
In this way it will be easier to debug parameters, since apache can be pretty bastard sometimes. | Here's a solution which will loop over key/value pairs in your URL:
```
RewriteRule ^cat_ap~([^~]+)~([^~]+)(.*)\.htm$ cat_ap$1?$1=$2 [N,QSA]
RewriteRule ^cat_ap(.*)\.htm$ /urban/cat_ap.php [L]
```
It grabs the first pair off the URL, then rewrites it to the exact same URL *without* that pair, adds the pair to the query string (`[QSA]`) and starts the rewriting process over again (`[N]`). When there are no more key/value pairs in the URL, it rewrites it to your script's location and terminates rewriting (`[L]`).
```
cat_ap~pnid~290~nid~96666~posters~Sports.htm => /urban/cat_ap.php?posters=Sports&nid=96666&pnid=290
cat_ap~PageNum_GetProduct~10~nid~290.htm => /urban/cat_ap.php?nid=290&PageNum_GetProduct=10
```
(Note that the order of parameters is reversed; this will only matter if the same parameter appears more than once.) | php mod rewrite | [
"",
"php",
"apache",
"mod-rewrite",
""
] |
I have found [Design patterns certification](http://www.brainbench.com/xml/bb/common/testcenter/taketest.xml?testId=426) at the Brainbehch.
I have heard from people who passed it, that there are many Language-specific patterns questions, mostly from Java and C++.
I think that this certification can:
* force me to improve my skills on Object oriented design and design patterns;
* improve and structure my knowledge of the domain;
* give real estimate of my knowledge, which is useful issue itself
The only confusion I have about this certification, is that I have to learn C++/Java language specific design patterns, while I mostly do PHP development and don't want to switch to C++/Java.
I'm familiar with Java & C++ syntax, read lots of books about different subjects with code snippets in this programming languages.
I think, that if I pass well all concepts except language specific patterns at certification, it won't be very good, because this concepts will gain quite low results.
What would you recommend in this particular circumstance? | This is personal opinion, but getting "certified" in something like design patterns is a bit like getting "certified" that you are a professional basketball player. If you are qualified, it will be obvious without a certification, and if you're inexperienced, you won't be able to get one anyway.
**The best way to understand design patterns is to gain real, practical experience of when they do and don't apply.** Alas, you won't get that without working on real software projects. Consider joining an open-source effort or starting your own project if you feel like your regular job doesn't provide enough of a technical challenge for this to be feasible.
Often times people are trying to fit square pegs into round holes when they advise you to use a particular design pattern. It will take a certain level of experience and competence on your part to evaluate whether they're right or not. | The purpose of certification is to verify that you have the knowledge and skills.
It seems to me that brainbench have made a mistake in adding tests of language-specific tests in an otherwise language-independent discipline.
Although a C++ expert I have limited experience in java. I took this OO design-patterns test to find that 13 of the 40 questions were on java-specific patterns (which I have obviously never used) . That is 1/3 of the questions were specific to a single language !! (there also was 1 question on C++ language-specific patterns). It seems to me that java-specific questions should be in a java-specific test. | Should I pass the BrainBench Design patterns certification? | [
"",
"php",
"design-patterns",
""
] |
Given the following code :
```
<body>
<img src="source.jpg" />
<p>
<img src="source.jpg" id ="hello" alt="nothing" />
<img src="source.jpg" id ="world"/>
</p>
</body>
```
What's the best way - using a regular expression (or better?) - to replace it so it becomes this:
```
<body>
<img src="source.jpg" id="img_0" />
<p>
<img src="source.jpg" id ="img_1" alt="nothing" />
<img src="source.jpg" id ="img_2"/>
</p>
</body>
```
In other words :
* All the `<image />` tags all gets populated by an `id` attribute.
* The `id` attribute should contain an incremented attribute (this is not really the problem though as its just part of the replace procedure)
I guess two passes are needed, one to remove all the existent `id` attributes and another to populate with new ones ? | I think the best approach is to use [`preg_replace_callback`](http://uk.php.net/manual/en/function.preg-replace-callback.php).
Also I would recommend a slightly more stringent `regexp` than those suggested so far - what if your page contains an `<img />` tag that does *not* contain an `id` attribute?
```
$page = '
<body>
<img src="source.jpg" />
<p>
<img src="source.jpg" id ="hello" alt="nothing" />
<img src="source.jpg" id ="world"/>
</p>
</body>';
function my_callback($matches)
{
static $i = 0;
return $matches[1]."img_".$i++;
}
print preg_replace_callback('/(<img[^>]*id\s*=\s*")([^"]*)/', "my_callback", $page);
```
Which produces the following for me:
```
<body>
<img src="source.jpg" />
<p>
<img src="source.jpg" id ="img_0" alt="nothing" />
<img src="source.jpg" id ="img_1"/>
</p>
</body>
```
The `regexp` has two capturing groups, the first we preserve, the second we replace. I've used lots of negative character classes (e.g. `[^>]*` = up to closing `>`) to make sure that `<img />` tags arn't *required* to have `id` attributes. | ```
<?php
$data = <<<DATA
<body>
<img src="source.jpg" />
<p>
<img src="source.jpg" id ="hello" alt="nothing" />
<img src="source.jpg" id ="world"/>
</p>
</body>
DATA;
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->strictErrorChecking = true;
$doc->standalone = true;
$doc->xmlStandalone = true;
$doc->formatOutput = true;
$doc->loadXML($data, LIBXML_NOWARNING | LIBXML_NOERROR);
$sNode = $doc->getElementsByTagName("img");
$id = 0;
foreach($sNode as $searchNode)
{
$searchNode->setAttribute('id', "img_$id");
$doc->importNode($searchNode);
$id++;
}
$result = $doc->saveHTML();
echo $result;
``` | RegEx for replacing and adding attributes to an HTML tag | [
"",
"php",
"regex",
"actionscript-3",
""
] |
How can I convert this XAML code into C# code?
```
<Window.Resources>
<DataTemplate x:Key="itemtemplate">
<TextBlock Text="{Binding Path=Text}"/>
</DataTemplate>
</Window.Resources>
``` | Try the following. Not an imperative WPF expert so you may need to alter this slightly
```
public void Example()
{
var factory = new FrameworkElementFactory(typeof(TextBlock));
factory.SetBinding(TextBlock.TextProperty, new Binding("Text"));
var dataTemplate = new DataTemplate();
dataTemplate.VisualTree = factory;
dataTemplate.Seal();
}
``` | The correct way to create DataTemplates from C# is to use a XamlReader and give it what you wrote in your question.
Which is unpleasant, to say the least. Sorry. | How can I convert this XAML code into C# code? | [
"",
"c#",
"wpf",
""
] |
I'm working an image processing website, instead of having lengthy jobs hold up the users browser I want all commands to return fast with a job id and have a background task do the actual work. The id could then be used to check for status and results (ie a url of the processed image). I've found a lot of distributed queue managers for ruby, java and python but I don't know nearly enough of any of those languages to be able to use them.
My own tests have been with shared mysql database to queue jobs, lock them to a worker, and mark them as completed (saving the return data in the db). It was just a messy prototype, and the entire time I felt as if I was reinventing the wheel (and not very elegantly). Does something exist in php (or that I can talk to RESTfully?) that I could use?
Reading around a bit more, I've found that what I'm looking for is a queuing system that has a php api, it doesn't have to be written in php. I've only found classes for use with Amazon's SQS, but not only is that not free, it's also quite latent sometimes (over a minute for a message to show up). | Have you tried ActiveMQ? It makes mention of supporting PHP via the Stomp protocol. Details are available on [the activemq site](http://activemq.apache.org/cross-language-clients.html).
I've gotten a lot of mileage out of the database approach your describing though, so I wouldn't worry too much about it. | Do you have full control over server?
MySQL queue could be fine in such case. Have a PHP script that is running constantly (in endless while loop), querying the MySQL database for new "tasks" and sleep()ing in between to reduce the load in idle time.
When each task is completed, mark it in the database and move to the next one.
To prevent that whole thing stops if your script crashes/exists (PHP memory overflow, etc.) you can, for example, place it in [inittab](http://en.wikipedia.org/wiki/Init) (if you use Linux as a server) and init will restart it automatically. | What are some good distributed queue managers in php? | [
"",
"php",
"queue",
"distributed",
""
] |
i'm after a way to remove the outline focus that firefox applies to my page:
<http://www.bevelite.com.au/test>
i've read that applying the following will fix this but can't seem to apply it to my code:
```
sIFR.replace(movie, {fixFocus: true});
```
my code:
```
sIFR.replace(univers47cl, {
selector: 'h1.test',
wmode: 'transparent',
css: [
'.sIFR-root { font-size: 20px; font-weight: 100; color: #000000; text-transform: uppercase; line-height: 20px; margin: 0 0 15px 0; padding: 0; }',
'a { text-decoration: none; }',
'a:link { color: #000000; text-decoration: none; }',
'a:hover { color: #000000; text-decoration: underline; }',
]
});
sIFR.replace(univers47cl, {
selector: 'h1',
wmode: 'transparent',
css: [
'.sIFR-root { font-size: 20px; font-weight: 100; color: #00b9f2; text-transform: uppercase; line-height: 20px; margin: 0 0 15px 0; padding: 0; }',
'a { text-decoration: none; }',
'a:link { color: #00b9f2; text-decoration: none; }',
'a:hover { color: #00b9f2; text-decoration: underline; }',
]
});
```
can anyone see where i could apply this to me code?
(sIRF documentation here > <http://wiki.novemberborn.net/sifr3/>) | Mathew Taylor's answer above is probably more accurate but your question is where to put that snippet in. Also, note in your snippet you had an extra trailing comma in your array 'css: []', you should watch out for those because they will get you in IE
```
sIFR.replace(univers47cl, {
selector: 'h1.test',
wmode: 'transparent',
fixFocus: true,
css: [
'.sIFR-root { font-size: 20px; font-weight: 100; color: #000000; text-transform: uppercase; line-height: 20px; margin: 0 0 15px 0; padding: 0; }',
'a { text-decoration: none; }',
'a:link { color: #000000; text-decoration: none; }',
'a:hover { color: #000000; text-decoration: underline; }'
]
});
sIFR.replace(univers47cl, {
selector: 'h1',
wmode: 'transparent',
fixFocus: true,
css: [
'.sIFR-root { font-size: 20px; font-weight: 100; color: #00b9f2; text-transform: uppercase; line-height: 20px; margin: 0 0 15px 0; padding: 0; }',
'a { text-decoration: none; }',
'a:link { color: #00b9f2; text-decoration: none; }',
'a:hover { color: #00b9f2; text-decoration: underline; }'
]
});
``` | If you are referring to the dotted outline on active links it can be removed like this:
```
a {
outline:0;
}
``` | sIFR 3: fixfocus: true? | [
"",
"javascript",
"css",
"firefox",
"sifr",
""
] |
When browsing through Facebook pages the header and fixed footer section remain visible between page loads AND the URL in the address bar changes accordingly. At least, that's the illusion I get.
How does Facebook achieve that technically speaking? | Refer to Mark Brittingham's answer for how to style it, although I don't think that is what you are asking here. I will give you the technical details on how it works (and why it is fairly brilliant).
Take a look at the status bar when you hover over the Profile link in the header...
> <http://www.facebook.com/profile.php?id=514287820&ref=profile>
That is where that <a> tag is pointed to. Now look at the address bar when you click it...
> <http://www.facebook.com/home.php#/profile.php?id=514287820&ref=profile>
Notice the "#" [fragment identifier/hash](http://en.wikipedia.org/wiki/Number_sign#Other_uses)? This basically proves that you haven't left the page and the previous request was made with AJAX. They are intercepting the click events on these links, and overriding the default functionality with something of their own.
To make this happen with Javascript, all you have to do is assign a click event handler to those links like so...
```
var header = document.getElementById('header');
var headerLinks = header.getElementsByTagName('a');
for(var i = 0, l = headerLinks.length; i < l; i++) {
headerLinks[i].onclick = function() {
var href = this.href;
//Load the AJAX page (this is a whole other topic)
loadPage(href);
//Update the address bar to make it look like you were redirected
location.hash = '#' + href;
//Unfocus the link to make it look like you were redirected
this.blur();
//Prevent the natural HTTP redirect
return false;
}
}
```
One fabulous benefit to this approach is that it allows the back button to be functional (with a little added trickery), which has traditionally been a painful side effect of chronic AJAX usage. I'm not 100% sure of what this trickery is, but I bet it's somehow able to detect when the browser modifies the fragment identifier (possibly by checking it every ~500 milliseconds).
As a side note, changing the hash to a value that can't be found within the DOM (via element ID) will scroll the page all the way to the top. To see what I'm talking about: you scroll down about 10 pixels from the top of Facebook, exposing half of the top menu. Click on one of the items, it will jump it back up to the top of the page as soon as the fragment identifier gets updated (without *any* window repaint/redraw delay). | One way to provide headers and footers that appear invariant is via CSS - here is an example of a fixed footer (notice the "position: fixed;"):
```
#Footer {
font-size:xx-small;
text-align:left;
width:100%;
bottom:0px;
position:fixed;
left:0px;
background-color: #CCCCCC;
border-top: 1px solid #999999;
padding:4px;
padding-right:20px;
color:#666666;
}
```
You'll want to make sure that you add some Margin-Bottom to your page divs (those that fill the main portion of the page) to leave room for the fixed footer (same with a header using Margin-Top).
This does *not* actually stay on the page but, because the positioning is so tight and invariant, it will appear as if it does unless your page loads take too long. I don't know if this is what FaceBook does but it will give you much the same effect. | How does Facebook keep the header and footer fixed while loading a different page? | [
"",
"javascript",
"html",
"ajax",
"facebook",
"navigation",
""
] |
How to use a link to call JavaScript code? | ```
<a onclick="jsfunction()" href="#">
```
or
```
<a onclick="jsfunction()" href="javascript:void(0);">
```
Edit:
The above response is really not a good solution, having learned a lot about JS since I initially posted. See [EndangeredMassa's answer](https://stackoverflow.com/a/688228/2227526) below for the better approach to solving this problem. | Unobtrusive JavaScript, no library dependency:
```
<html>
<head>
<script type="text/javascript">
// Wait for the page to load first
window.onload = function() {
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function() {
// Your code here...
//If you don't want the link to actually
// redirect the browser to another page,
// "google.com" in our example here, then
// return false at the end of this block.
// Note that this also prevents event bubbling,
// which is probably what we want here, but won't
// always be the case.
return false;
}
}
</script>
</head>
<body>
<a id="mylink" href="http://www.google.com">linky</a>
</body>
</html>
``` | How to use a link to call JavaScript? | [
"",
"javascript",
""
] |
Well i have a list of objects `List<UserDC>` now i would want to display this in some kind of grid so i tryed the `GridView`
```
GridView1.DataSource = list
GridView1.DataBind()
```
Well that did work but now i want to hide some columns but that does not seem to be so easy :
```
GridView1.Columns(0).Visible = False
GridView1.Columns(1).Visible = False
GridView1.Columns(2).Visible = False
```
this just gives me a exception `ArgumentOutOfRangeException` how do i make it generate the columns before it displays the list so i can filter out those that i dont want? | To hide the GridView columns, you can use the **GridView\_RowDataBoundEvent** and hide the unwanted columns.
You can hide the Column Header, Data Rows OR BOTH by checking the "RowType" property in this event. | Works OK for me. Here is a suggestion for you to check.
Since this is VB .NET code, I assume you have VS 2005 or 2008.
Set a breakpoint at GridView1.Columns(0).Visible = False
Using the Watch Window, create a watch for GridView1.Columns. Expand "base", What is the value of "Count"? It is likely to be ZERO, means you do not have any columns. The may be the reason you have "ArgumentOutOfRangeException".
Is your data binding to "list" working? | How to set visibility of GridView Columns in ASP.NET? | [
"",
"c#",
"asp.net",
"vb.net",
""
] |
How can I make my own event in C#? | Here's an example of creating and using an event with C#
```
using System;
namespace Event_Example
{
//First we have to define a delegate that acts as a signature for the
//function that is ultimately called when the event is triggered.
//You will notice that the second parameter is of MyEventArgs type.
//This object will contain information about the triggered event.
public delegate void MyEventHandler(object source, MyEventArgs e);
//This is a class which describes the event to the class that recieves it.
//An EventArgs class must always derive from System.EventArgs.
public class MyEventArgs : EventArgs
{
private string EventInfo;
public MyEventArgs(string Text)
{
EventInfo = Text;
}
public string GetInfo()
{
return EventInfo;
}
}
//This next class is the one which contains an event and triggers it
//once an action is performed. For example, lets trigger this event
//once a variable is incremented over a particular value. Notice the
//event uses the MyEventHandler delegate to create a signature
//for the called function.
public class MyClass
{
public event MyEventHandler OnMaximum;
private int i;
private int Maximum = 10;
public int MyValue
{
get
{
return i;
}
set
{
if(value <= Maximum)
{
i = value;
}
else
{
//To make sure we only trigger the event if a handler is present
//we check the event to make sure it's not null.
if(OnMaximum != null)
{
OnMaximum(this, new MyEventArgs("You've entered " +
value.ToString() +
", but the maximum is " +
Maximum.ToString()));
}
}
}
}
}
class Program
{
//This is the actual method that will be assigned to the event handler
//within the above class. This is where we perform an action once the
//event has been triggered.
static void MaximumReached(object source, MyEventArgs e)
{
Console.WriteLine(e.GetInfo());
}
static void Main(string[] args)
{
//Now lets test the event contained in the above class.
MyClass MyObject = new MyClass();
MyObject.OnMaximum += new MyEventHandler(MaximumReached);
for(int x = 0; x <= 15; x++)
{
MyObject.MyValue = x;
}
Console.ReadLine();
}
}
}
``` | I have a full discussion of events and delegates in my [events article](http://csharpindepth.com/Articles/Chapter2/Events.aspx). For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:
```
public event EventHandler Foo;
```
If you need more complicated subscription/unsubscription logic, you can do that explicitly:
```
public event EventHandler Foo
{
add
{
// Subscription logic here
}
remove
{
// Unsubscription logic here
}
}
``` | How can I make my own event in C#? | [
"",
"c#",
".net",
"events",
""
] |
When implementing IDisposable correctly, most implementations, including the framework guidelines, suggest including a `private bool disposed;` member in order to safely allow multiple calls to `Dispose()`, `Dispose(bool)` as well as to throw [ObjectDisposedException](http://msdn.microsoft.com/en-us/library/system.objectdisposedexception.aspx) when appropriate.
This works fine for a single class. However, when you subclass from your disposable resource, and a subclass contains its own native resources and unique methods, things get a little bit tricky. Most samples show how to override `Dipose(bool disposing)` correctly, but do not go beyond that to handling `ObjectDisposedException`.
There are two questions that I have in this situation.
---
First:
The subclass and the base class both need to be able to track the state of disposal. There are a couple of main options I know of -
* 1) Declare private bool disposed; in both classes. Each class tracks its own this.disposed, and throws as needed.
* 2) Use protected bool Disposed { get; private set; } instead of a field. This would let the subclass check the disposed state.
* 3) Provide some protected helper method to check the disposed state, and throw by pulling the current type name via reflection if the object is disposed.
The advantages as disadvantages I see to each by option are:
* 1) This "smells" to me since it contains duplicated booleans, but seems to work fine. I often use this when subclassing other code.
* 2) This takes out the duplicated booleans, but is not the way the design guidelines books are written, etc. This is what I typically use, though, since it keeps it a single point for state.
* 3) This seems like the cleanest option to me, but doesn't appear in standard guidelines. It may be a little less expected of an approach than others from users of the class.
I, at one point or another, have tried using all three of these approaches. I would like to know advantages and disadvantages to the three approaches, as well as any other ideas for a cleaner, better way to handle this. What choice would you make in handling this, and why?
---
Second:
When throwing the `ObjectDisposedException`, what do you use for the name argument? I know the "typical" method call is:
```` ```
throw new ObjectDisposedException(GetType().FullName);
``` ````
There is a comment [on this page](http://msdn.microsoft.com/en-us/library/system.objectdisposedexception.aspx) from a Microsoft employee suggesting that implementing the concrete class's full name is the appropriate usage.
In the third option above, this would be the only meaningful choice. However, if the class implements the throwing itself, you could potentially return the name of the class that defines the method that was called. (ie: the base class could return the base class's name, not the concrete subclass)
I don't think this is a good idea - but I ran into this on some code written by somebody else. Are there advantages or disadvantages to having the name of the class implementing the method returned? | I typically implement the first option. Indeed, it seems to be what the design guidelines recommend. The reason isn't immediately apparent, but I consider it a good one nonetheless: any implementer of the class should have the same sort of protection against the case where the object is disposed as general consumers. In other words, it's best not to *assume* that whoever is implementing a derived class knows precisely when they can call a certain method, whose successful execution may or may not depend on whether the object has already been disposed or not (though ideally this should be documented via XML comments anyway).
Regarding your second question, I would again stick with the recommended practice of passing `GetType().FullName`, especially since it's used in the core .NET framework. Even if you think alternative methods are more appropriate, I think it's best to stick to the method used in the .NET framework for the sake of consistency.
To conclude: as with all guidelines, it's clearly up to you how you want to implement a certain design feature, though unless you have a particularly good reason it's highly advisable just to stick with them. In both these situations, it probably wouldn't do a great deal of harm to utilise some of the alternatives you suggested in your post, so long as they are used consistently and preferably documented to the user. | > Declare private bool disposed; in both classes. Each class tracks its own this.disposed, and throws as needed.
It is the practical solution when you are unable to modify the base class.
> Use protected bool Disposed { get; private set; } instead of a field. This would let the subclass check the disposed state.
Why not make it public and call it IsDisposed instead? Then you would be doing the same thing as System.Windows.Forms.Control. This is a good solution when you can modify the base class.
> you could potentially return the name of the class that defines the method
No. The example code you referenced used "GetType().FullName". This is always the name of the most derived type, not the type that implements the particular method. | Handling ObjectDisposedException correctly in an IDisposable class hierarchy | [
"",
"c#",
".net",
"idisposable",
""
] |
Currently I have a test class called TestClass.cs in C:\Projects\TestProject\TestClass.cs
I also have an Xml file in C:\Projects\TestProject\config\config.xml
In TestClass.cs, I have a test method to load the Xml from the filesystem like so:
`XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Path.Combine(Assembly.GetExecutingAssembly().Location, "config\config.xml"));`
Unfortunately, the Location property gives me the value:
C:\Projects\TestProject\TestResults\klaw\_[computernamehere] [time here]\
instead of what I want, which is C:\Projects\TestProject\
I've tried Assembly.GetExecutingAssembly().CodeBase as well with similar results.
Any ideas? | You need to mark this file with the DeploymentItemAttribute if you're using MSTest. This means it will be copied with the DLL. | Since this is a test, how about making the file an embedded resource? You can then read the embedded resource at runtime with the following code:
```
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
```
The resource is normally the namespace + filename. But you can work this out by running
the following code in the debugger:
```
AssemblyGetExecutingAssembly().GetManifestResourceNames();
```
This returns a list of embedded resources. | .NET: Getting the absolute path for a file when running VS Team Test | [
"",
"c#",
".net",
"visual-studio-2008",
"unit-testing",
""
] |
Given a DateTime and a DayOfWeek should return the date of the last DayOfWeek of that month.
E.g.
1st-March-2009 and Sunday would return 29th-March-2009 | Can't find a handy one-liner but this one works:
```
static DateTime LastDayOfWeekInMonth(DateTime day, DayOfWeek dow)
{
DateTime lastDay = new DateTime(day.Year, day.Month, 1).AddMonths(1).AddDays(-1);
DayOfWeek lastDow = lastDay.DayOfWeek;
int diff = dow - lastDow;
if (diff > 0) diff -= 7;
System.Diagnostics.Debug.Assert(diff <= 0);
return lastDay.AddDays(diff);
}
``` | <http://datetimeextensions.codeplex.com/> has a Last(dayOfWeek) extension method that will do this for you
Test included :-) | Calculate the last DayOfWeek of a month | [
"",
"c#",
"datetime",
""
] |
I have an asp.net ajax website, it full of things happen on the same page without page reload, such as sorting records, paging,...
When the user go to another page in the same site and press the browser back button, how can i make the browser save the page state to return to it with the preselected options such as sorting option, page number in the paging.
I knew that there is a history control in the new .net 3.5 but its working in the same page not while navigating from a page to another.
Also i am looking for a solution which work in all browsers.
Thanks, | You dont need 3.5 for the history control, [check ScottGu's blog here](https://weblogs.asp.net/scottgu/Tip_2F00_Trick_3A00_-Enabling-Back_2F00_Forward_2D00_Button-Support-for-ASP.NET-AJAX-UpdatePanel)
Also check if [this article helps](https://web.archive.org/web/20191229153408/http://geekswithblogs.net:80/frankw/archive/2008/10/29/enable-back-button-support-in-asp.net-ajax-web-sites.aspx) | You do what the history plugin suggested above does. I'm assuming under the hood, this is what is going on. When your async-postback comes back to the client side for example, do a JavaScript call to window.location = 'somePage.aspx#anchor1' (an old school HTML anchor), then the next async-postback once back on the client would do window.location = 'somePage.aspx#anchor2', etc. GMail does this when it redirects to your inbox or other labels or folders in your e-mail.
Hope that helps,
Nick | How to: Back button support "Ajax" | [
"",
".net",
"asp.net",
"javascript",
"html",
"ajax.net",
""
] |
Is it possible to dynamically place text on an image in php?
And then send it to an rss feed? | Yes, can use either the [GD](http://www.php.net/gd) functions or the [ImageMagick](http://www.php.net/imagemagick) functions, depending on which is installed on your server and which you prefer.
Using GD it would go something like this:
```
<?php
$img = imagecreatefromjpeg('my.jpg');
$textColor = imagecolorallocate($img, 0, 0, 0); // black text
imagefttext($img, 13, 0, 105, 55, $textColor, './arial.ttf', 'Hello World');
// Output image to the browser
header('Content-Type: image/jpeg');
imagejpeg($img);
// Or save to file
imagejpeg($img, 'my-text.jpg');
imagedestroy($img);
?>
```
Edit:
To put the image into your RSS feed you would save it to a file and put the URL into your feed. | Of course. With [`imagefttext()`](http://www.php.net/manual/en/function.imagefttext.php) from GD. You'll need TTF files though. | Text on a image | [
"",
"php",
"image",
"text",
""
] |
I want to save my dates in sql2005 as dates (without hour minutes and seconds).
I want to do this because the between function isn't always correct if the hours, minutes and seconds are filled in.
but neither datetime nor smalldatetime allows this, in 2008 you have the Date column which can do this.
I've also found this question which helps me out but I don't like the casting to execute my queries: [How to remove the time portion of a datetime value (SQL Server)?](https://stackoverflow.com/questions/2775/whats-the-best-way-to-remove-the-time-portion-of-a-datetime-value-sql-server) | The non-casting way:
```
SET @d = DATEADD(dd, 0, DATEDIFF(dd, 0, @dt))
```
This adds the number of days between 0 and your date to 0, resulting in the time-part to be zero.
If that is faster than the explicit CAST approach must be tested. The use of 0 suggests some implicit casting will be done in this expression. | ```
SELECT CONVERT (date, GETDATE()) -- Without hours, minutes and seconds.
```
For more details, please refer to <http://msdn.microsoft.com/en-us/library/ms188383.aspx> | Save DateTime in mssql 2005 without hours, minutes and seconds | [
"",
"sql",
"sql-server",
"datetime",
""
] |
I have a list of controls (\_controlList) and from that list of controls I want to get the ones that derive from a given class. So I have code that looks like this.
```
List<Control> _controlList = new List<Control>();
public Control[] ControlsThatIsA(Type soughtType)
{
List<Control> result = new List<Control>();
foreach (Control control in _controlList)
{
// This would have been nice but doesn't compile
//////////////
// if (control.GetType() is soughtType)
{
result.Add(control);
}
}
return result.ToArray();
}
```
Any thoughts. I don't have to pass in the Type, it could be the string name of the class | First, I'd probably use generics:
```
public T[] ControlsOfType<T>() where T : Control
{
List<T> result = new List<T>();
foreach (Control control in _controlList)
{
if (control is T)
{
result.Add((T)control);
}
}
return result.ToArray();
}
```
Or in .NET 3.5:
```
return _controlList.OfType<T>().ToArray();
```
If you need to use `Type`, then `IsAssignableFrom` is your friend, in particular:
```
if(soughtType.IsAssignableFrom(control.GetType())) {
//...
}
``` | the C# is operator already does a type test (like the Vb TypeOf operator), so it expects something like
if (control is MyNamespace.MyControl)
this is fine if you know the type you are looking for at compile time, but no good for your situation.
Also, if your test was changed to do a reference equals test (sorry, I'm a VB programmer really, the VB operator would be IS but I don't know the c# one) then your test would only return true if the control was the type tested for, not it it was inherited from the soughtType.
Try
control.GetType().IsSubClassOf(soughtType)
Note that IsSubClassOf won't return true if control is one of soughtType, but your question did ask to find only controls that inherited from soughtType. | How do you find out if a control derives from a class | [
"",
"c#",
""
] |
I want to develop an ASP.NET application that can detect the user logged on a Window Domain. These credentials are going to be used to logging on the ASP.NET application.
How can I do this?
Thanks! | In IIS, turn on Integrated Windows Authentication, and in code, if you use:
```
Request.ServerVariables["LOGON_USER"]
```
it will return the windows username of the logged in user, i.e. MYDOMAIN\MYUSERNAME | Here is C# code I use to authenticate against the Active Directory
```
using System;
using System.DirectoryServices;
namespace XYZcompany.Enterprise
{
public class AuthenicationMgr
{
private static readonly int AD_ERR_LOGON_FAIL = -2147023570;
private static readonly string _path = "LDAP://xxx.yyy.ggg";
private static readonly string _domain = "xxx.yyy.ggg";
public static bool IsAuthenticated(string username, string pwd)
{
bool authenticatedFlag = true;
string domainAndUsername = _domain + "\\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result == null)
{
authenticatedFlag = false;
}
else
{
authenticatedFlag = true;
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
if (ex.ErrorCode == AD_ERR_LOGON_FAIL)
{
authenticatedFlag = false;
}
else
{
throw new ApplicationException("Unable to authenticate user due to system error.", ex);
}
}
return authenticatedFlag;
}
}
}
``` | Detect user logged on a computer using ASP.NET app | [
"",
"c#",
"asp.net",
"active-directory",
"windows-authentication",
""
] |
I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications? | try python [curses](http://docs.python.org/howto/curses.html) module , it is a command-line graphic operation library. | Take a look at [Curses Programming in Python](http://docs.python.org/howto/curses.html) and [this](http://docs.python.org/library/curses.html) as well. | How do I make a command line text editor? | [
"",
"python",
"text-editor",
"tui",
""
] |
We have installed Apache 2.2 on a windows server 2003.
We want to make apache able to write to files on the disk but we don't know as what user Apache works as.
How do we allow Apache to write to files on a Windows server 2003?
UPDATE:
The user is running as 'SYSTEM' and we have tried giving that user full permission to all folders and files. Also we have given 'Everyone' full permission to all folders and files. We have restarted Apache, cleared all cookies, restarted IE and still we get a message, from phpMyAdmin, that we don't have write permission. | Look in
Start --> Administrative Tools --> Services
in that list you should see the Apache Service (assuming you installed it as a service)
Right click properties, Log On tab should tell you who it's logged on as. | Have you tried giving the "Everyone"-group access to the files? Do not forget to reset this setting in production.
To see which user apache runs under, use the task manager. | Apache on windows server can't write to file | [
"",
"php",
"apache",
"apache2",
""
] |
I'm writing a time-critical piece of code in C# that requires me to convert two unsigned integers that define an inclusive range into a bit field. Ex:
```
uint x1 = 3;
uint x2 = 9;
//defines the range [3-9]
// 98 7654 3
//must be converted to: 0000 0011 1111 1000
```
It may help to visualize the bits in reverse order
The maximum value for this range is a parameter given at run-time which we'll call `max_val`. Therefore, the bit field variable ought to be defined as a `UInt32` array with size equal to `max_val/32`:
```
UInt32 MAX_DIV_32 = max_val / 32;
UInt32[] bitArray = new UInt32[MAX_DIV_32];
```
Given a range defined by the variables `x1` and `x2`, what is the fastest way to perform this conversion? | Try this. Calculate the range of array items that must be filled with all ones and do this by iterating over this range. Finally set the items at both borders.
```
Int32 startIndex = x1 >> 5;
Int32 endIndex = x2 >> 5;
bitArray[startIndex] = UInt32.MaxValue << (x1 & 31);
for (Int32 i = startIndex + 1; i <= endIndex; i++)
{
bitArray[i] = UInt32.MaxValue;
}
bitArray[endIndex] &= UInt32.MaxValue >> (31 - (x2 & 31));
```
May be the code is not 100% correct, but the idea should work.
---
Just tested it and found three bugs. The calculation at start index required a mod 32 and at end index the 32 must be 31 and a logical and instead of a assignment to handle the case of start and end index being the same. Should be quite fast.
---
Just benchmarked it with equal distribution of x1 and x2 over the array.
Intel Core 2 Duo E8400 3.0 GHz, MS VirtualPC with Server 2003 R2 on Windows XP host.
```
Array length [bits] 320 160 64
Performance [executions/s] 33 million 43 million 54 million
```
---
One more optimazation x % 32 == x & 31 but I am unable to meassure a performance gain. Because of only 10.000.000 iterations in my test the fluctuations are quite high. And I am running in VirtualPC making the situation even more unpredictable. | My solution for setting a whole range of bits in a BitArray to true or false:
```
public static BitArray SetRange(BitArray bitArray, Int32 offset, Int32 length, Boolean value)
{
Int32[] ints = new Int32[(bitArray.Count >> 5) + 1];
bitArray.CopyTo(ints, 0);
var firstInt = offset >> 5;
var lastInt = (offset + length) >> 5;
Int32 mask = 0;
if (value)
{
// set first and last int
mask = (-1 << (offset & 31));
if (lastInt != firstInt)
ints[lastInt] |= ~(-1 << ((offset + length) & 31));
else
mask &= ~(-1 << ((offset + length) & 31));
ints[firstInt] |= mask;
// set all ints in between
for (Int32 i = firstInt + 1; i < lastInt; i++)
ints[i] = -1;
}
else
{
// set first and last int
mask = ~(-1 << (offset & 31));
if (lastInt != firstInt)
ints[lastInt] &= -1 << ((offset + length) & 31);
else
mask |= -1 << ((offset + length) & 31);
ints[firstInt] &= mask;
// set all ints in between
for (Int32 i = firstInt + 1; i < lastInt; i++)
ints[i] = 0;
}
return new BitArray(ints) { Length = bitArray.Length };
}
``` | Converting a range into a bit array | [
"",
"c#",
"bit-manipulation",
"bitarray",
""
] |
How would one display what line number caused the error and is this even possible with the way that .NET compiles its .exes?
If not is there an automated way for Exception.Message to display the sub that crapped out?
```
try
{
int x = textbox1.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
``` | Use `ex.ToString()` to get the full stack trace.
You must compile with debugging symbols (.pdb files), even in release mode, to get the line numbers (this is an option in the project build properties). | To see the stacktrace for a given Exception, use [e.StackTrace](http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx)
If you need more detailed information, you can use the [System.Diagnostics.StackTrace](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx) class (here is some code for you to try):
```
try
{
throw new Exception();
}
catch (Exception ex)
{
//Get a StackTrace object for the exception
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
}
```
This will only work if there is a pdb file available for the assembly. See the project properties - build tab - Advanced - Debug Info selection to make sure there is a pdb file. | Show line number in exception handling | [
"",
"c#",
".net",
"exception",
"line-numbers",
""
] |
I need to pass information from one exe to another exe. Is it possible ?
If it is possible, can you give me idea to solve this problem.
here i need to send some string msg to another exe . the another exe should recive that msg and it should perform some operation depends on the that string msg... | You can do this is a number of ways, so just to name a few:
* Shared files
* A common database
* Remoting
* Sockets
* WCF
so you probably have to be a bit more specific. What are you trying to accomplish? | > With program A:
> Create a file.
> Write your data in it
> Close the file
---
> With program B:
> While(file\_in\_use or empty) wait
> Open the file
> Read the data you need
> Close the file
---
There is probably a better way to do this. Perhaps with sockets? This is just the only one I am remembering since I just woke up. | information exchange | [
"",
"c#",
".net",
""
] |
[http://php.net/glob](https://www.php.net/glob)
The documentation page on glob() has this example:
```
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
```
But to be honest, I don't understand how this can work.
The array produced by glob("\*.txt") will be traversed, but where does this array come from? Is glob() reading a directory? I don't see that anywhere in the code. Glob() looks for all matches to \*.txt
But where do you set where the glob() function should look for these strings? | Without any directory specified glob() would act on the current working directory (often the same directory as the script, but not always).
To make it more useful, use a full path such as glob("/var/log/\*.log"). Admittedly the PHP documentation doesn't make the behaviour clear, but glob() is a [C library function](http://man.cx/glob(3posix)), which is where it originates from. | Something useful I've discovered with `glob()`, if you want to traverse a directory, for example, for images, but want to match more than one file extension, examine this code.
```
$images = glob($imagesDir . '*' . '.{jpg,jpeg,png,gif}', GLOB_BRACE);
```
The `GLOB_BRACE` flag makes the braces sort of work like the `(a|b)` regex.
One small caveat is that you need to list them out, so you can't use regex syntax such as `jpe?g` to match `jpg` or `jpeg`. | Don't get the glob function in PHP | [
"",
"php",
"filesystems",
""
] |
I have a car and when accelerating i want the speed to increse "slowly"..
After looking at a few sites i came to the conclusion that the SmoothStep method could be used to do that?
I pretty much know how to move textures and stuff, so an example where smoothstep is used to increase value in a float or something like that, would be extremely helpful!
Thanks in advance :)
I think it is sad there isnt examples for all the methods in the MSDN library. | SmoothStep won't help you here. SmoothStep is a two value interpolation function. It does something similar to a sinus interpolation. It will accelerate slowly have a sharp speed at around x=0.5 and then slow down to the arrival (x=1.0).
Like the following:
[](https://i.stack.imgur.com/5cKkt.png)
This is approximate, the real function don't have these exact numbers.
Yes you could use the x=0..0.5 to achieve the effect you want, but with very little control over the acceleration curve.
If you want to really accelerate a car or any other object, your best bet would be to keep track of acceleration and velocity by yourself.
```
class Car : GameComponent
{
public override void Update(GameTime time)
{
velocity += acceleration * time.ElapsedGameTime.TotalSeconds;
position += velocity * time.ElapsedGameTime.TotalSeconds;
}
Vector3 position;
Vector3 velocity;
Vector3 acceleration;
}
```
position, velocity and acceleration being Vector2 or Vector3 depending on how many dimension your game state is using. Also, please note this form of integration is prone to slight math errors. | From [this documentation](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.mathhelper.smoothstep.aspx) it looks like SmoothStep takes 3 arguments - the two values you want to move between and the amount between them which probably needs to be between 0 and 1.
So say you have a float f that increments linearly from 0 to the destination speed over a period of time. instead of using f directly as the speed, using SmoothStep would look like this:
```
float speed = MathHelper.SmoothStep(0, destSpeed, f/destSpeed);
```
It really is amazing how bad this documentation is. | XNA MathHelper.SmoothStep? How does it work? | [
"",
"c#",
"xna",
"smoothstep",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.